所以我有这样的整数的列表:如何从列表中选择随机整数,与以前不同?
list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
我想从它选择与选择随机整数:
item = random.choice(list)
但我如何才能确保下一次我这样做,它是不同的项目?我不想从我的列表中删除项目。
所以我有这样的整数的列表:如何从列表中选择随机整数,与以前不同?
list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
我想从它选择与选择随机整数:
item = random.choice(list)
但我如何才能确保下一次我这样做,它是不同的项目?我不想从我的列表中删除项目。
如果您无论如何都需要它们,只是希望它们以随机顺序排列(但您不想更改列表),或者如果您对要抽样的项目数量没有上限(除了列表大小):
import random
def random_order(some_list):
order = list(range(len(some_list)))
random.shuffle(order)
for i in order:
yield some_list[i]
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for item in random_order(my_list):
... # do stuff
或者,你可以使用它像这样:
order = random_order(my_list)
some_item = next(order)
some_item = next(order)
...
创建一个发电机,从先前产生的选择检查:
import random
def randomNotPrevious(l):
prev = None
while True:
choice = random.choice(l)
if choice != prev:
prev = choice
yield choice
>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> randomLst = randomNotPrevious(l)
>>> next(randomLst)
1
>>> next(randomLst)
5
>>> next(randomLst)
3
>>> next(randomLst)
6
>>> next(randomLst)
5
你可以使用'random.sample()'。看到这个[链接](http://stackoverflow.com/questions/22842289/python-generate-n-unique-random-numbers-within-a-range) –
当你的问题得到解决时,这有点烦人编码解决方案。我已经在这里发布了一个答案,如果你仍然需要它:https://repl.it/ChS5 –