我的脚本的目的是创建一个累进数字的列表:
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
但我以为我错了。 有人能帮忙吗?在
您发布给自己问题的答案不起作用,因为它将元素与
list
中该元素的索引进行比较。因此,当您测试[0, 1, 2, 3, 4]
是否已被洗牌时,它的工作原理是生成exampleList
,其中range
从0
开始。在但是,如果您从任何其他
list
开始,那么您的解决方案将无法工作,原因如上所述。在要使其工作,您需要复制原始的
list
,这样您就可以将其作为已更改内容的参考。在然后,当任何元素都处于同一位置时,您需要继续洗牌。在
很简单,代码如下:
当我运行它
^{pr2}$3
次时,我得到了shfld
的三个结果:这些都是有效的!在
您的问题是将索引与列表项混合在一起,并在修改列表时对其进行迭代。在
最后,我采取了一种不同的方法,我确信这一点都不优雅,但至少它是有效的。 我设置了一个内部计数器,如果索引与该值不同,则该计数器将计数。 如果内部计数器达到我的总数,这意味着它是好的去。否则,在tot迭代之后,它再次洗牌e重新启动。在
相关问题 更多 >
编程相关推荐