我的脚本的目的是创建一个渐进数字列表:
examplelst=list(range(5))
然后,在导入随机和随机播放后,我想随机化列表:
shuffle(examplelst)
然后我需要检查一个值是否仍然在其起始位置,例如:
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
我认为这会奏效,但我错了。有人能帮忙吗?
您的问题是您将索引与列表项混合并在修改它时迭代列表。
done = False
while !done:
if next((item for i, item in enumerate(examplelst) if i == item), None) is None:
done = True
else:
shuffle(examplelst)
最后我采取了一种不同的方法,我确信它根本不优雅,但至少它起作用。我设置了一个内部计数器,如果索引与值不同,则计数器会上升。如果内部计数器达到我的总数,这意味着它是好的。否则,在完成迭代后,它再次重新启动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
您发布到自己的问题的答案不起作用,因为它将元素与list
中该元素的索引进行比较。因此,当你测试[0, 1, 2, 3, 4]
是否已被洗牌时,它会起作用,因为你从exampleList
开始用range
生成0
。
但是,如果您从任何其他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
的这三个结果:
[1, 0, 3, 4, 2]
[1, 3, 4, 0, 2]
[4, 0, 3, 1, 2]
这些都是有效的!