我想用随机值遍历列表。但是,我希望在下一次试用时将已被挑选的项目从列表中删除,这样我就可以避免连续挑选相同的项目;但应该在之后再次添加回来。
请帮助我在这个简单的示例中展示这一点。 谢谢
import random
l = [1,2,3,4,5,6,7,8]
for i in l:
print random.choice(l)
最佳答案
两者都适用于非唯一元素列表:
def choice_without_repetition(lst):
prev = None
while True:
i = random.randrange(len(lst))
if i != prev:
yield lst[i]
prev = i
或
def choice_without_repetition(lst):
i = 0
while True:
i = (i + random.randrange(1, len(lst))) % len(lst)
yield lst[i]
用法:
lst = [1,2,3,4,5,6,7,8]
for x in choice_without_repetition(lst):
print x
关于python - 如何从列表中随机选择项目,同时避免连续选择相同的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34769801/