2016-07-29 43 views
5

所以我有这样的整数的列表:如何从列表中选择随机整数,与以前不同?

list = [1, 2, 3, 4, 5, 6, 7, 8, 9] 

我想从它选择与选择随机整数:

item = random.choice(list) 

但我如何才能确保下一次我这样做,它是不同的项目?我不想从我的列表中删除项目。

+2

你可以使用'random.sample()'。看到这个[链接](http://stackoverflow.com/questions/22842289/python-generate-n-unique-random-numbers-within-a-range) –

+0

当你的问题得到解决时,这有点烦人编码解决方案。我已经在这里发布了一个答案,如果你仍然需要它:https://repl.it/ChS5 –

回答

2

如果你想要n列表中的不同随机值,请使用random.sample(list, n)

+1

对不起,我说这很糟糕,但我需要的项目是不同的每一次,不只是不同于最后一个项目 – mahifoo

+1

@mahifoo:我懂了。如果你在清单中的项目用完了,怎么办? – Lynn

+0

@Lynn该列表有很多项目,我只需要其中的几个。它不会用完 – mahifoo

1

如果您无论如何都需要它们,只是希望它们以随机顺序排列(但您不想更改列表),或者如果您对要抽样的项目数量没有上限(除了列表大小):

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) 
... 
0

创建一个发电机,从先前产生的选择检查:

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