从列表中随机删除两个相邻值

2024-05-13 21:04:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了函数pop(),它将从列表中删除一个值。但是,我想从列表中随机删除两个值,但两个数字必须相邻。例如,在[1, 2, 3, 4, 5]的列表中,如果我随机选择了2pop(),我还想删除13

我需要存储数字(p和q),以便以后计算,以下是我目前的代码:

nlist = [1, 2, 3, 4, 5]
shuffle(nlist)

while nlist:
    p = nlist.pop(random.randrange(len(nlist)))
    #save p and one adjacent value (q) within this loop
    #remove p and q from list

Tags: and函数代码列表lensave数字random
3条回答

删除元素时需要处理一些边缘情况,即p是列表中的第一个或最后一个元素。它使用一个方便的random函数choice来确定您选择的相邻元素

while len(nlist) > 1:
    # the number to remove
    p_index = random.randrange(len(nlist))
    if p_index == 0:
        q_index = p_index + 1
    elif p_index == len(nlist) - 1:
        q_index = p_index - 1
    else:
        q_index = p_index + random.choice([-1, 1])
    p, q = nlist[p_index], nlist[q_index]
    nlist.pop(p_index)
    nlist.pop(q_index)
    return p, q

您可以尝试以下方法:

from random import randint
nlist = [1, 2, 3, 4, 5]
data=randint(0,len(nlist)-2)
print([j for i,j in enumerate(nlist) if i not in range(data,data+2)])

输出:

#[3, 4, 5]
#[1, 4, 5]
#[1, 2, 5]

您可以选择randrange跨一个小于列表长度的索引,然后弹出同一索引两次:

pop_index = random.randrange(len(nlist)-1)
p = nlist.pop(pop_index)
q = nlist.pop(pop_index)

相关问题 更多 >