如何确保在洗牌后,所有的值都实际更改了索引?(Python3.6)

2024-09-30 03:25:36 发布

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

我的脚本的目的是创建一个累进数字的列表:

examplelst=list(range(5))

然后,在导入random和shuffle之后,我想随机排列列表:

^{pr2}$

然后我需要检查某个值是否仍处于起始位置,例如:

before shuffling: [0,1,2,3,4]
after shuffling: [3,0,2*,4,1]

在这种情况下,值“2”仍然具有索引2。 如果发生这种情况,我想再次洗牌,直到每个索引都随机更改。 我目前的做法是:

done=False
shuffle(examplelst)

while not done:
    for i in examplelst:
        if examplelst[i]==int(i):
            shuffle(examplelst)
            print ('shuffled')
        else:
            done=True
if done == True:
    continue with my stuff knowing that the list is properly shuffled

但我以为我错了。 有人能帮忙吗?在


Tags: 目的脚本true列表if情况range数字
3条回答

您发布给自己问题的答案不起作用,因为它将元素与list中该元素的索引进行比较。因此,当您测试[0, 1, 2, 3, 4]是否已被洗牌时,它的工作原理是生成exampleList,其中range0开始。在

但是,如果您从任何其他list开始,那么您的解决方案将无法工作,原因如上所述。在

要使其工作,您需要复制原始的list,这样您就可以将其作为已更改内容的参考。在

然后,当任何元素都处于同一位置时,您需要继续洗牌。在

很简单,代码如下:

import random
lst = list(range(5))
shfld = lst[:]
while any(lst[i] == shfld[i] for i in range(len(lst))):
    random.shuffle(shfld)

当我运行它3次时,我得到了shfld的三个结果:

^{pr2}$

这些都是有效的!在

您的问题是将索引与列表项混合在一起,并在修改列表时对其进行迭代。在

done = False
while !done:
    if next((item for i, item in enumerate(examplelst) if i == item), None) is None:
        done = True
    else:
        shuffle(examplelst)

最后,我采取了一种不同的方法,我确信这一点都不优雅,但至少它是有效的。 我设置了一个内部计数器,如果索引与该值不同,则该计数器将计数。 如果内部计数器达到我的总数,这意味着它是好的去。否则,在tot迭代之后,它再次洗牌e重新启动。在

done=False

while not done:
    shuffle(examplelst)
    intcount=0
    for i, item in enumerate(examplelst):
        #print (i, item)
        if i != item:
            intcount=intcount+1
            print (intcount)
            if intcount == total:
                done=True
        else:
            shuffle(examplelst)
if done == True:
    continue with my stuff knowing that the list is properly shuffled

相关问题 更多 >

    热门问题