我正在尝试创建一个函数,从列表中随机选择项目,并在每次运行时创建一个带有随机项目顺序的新列表。我相信我已经完成了大部分工作,但是,我错过了一种方法来确保当我的函数运行时,它总是只生成列表中的每个项目中的一个而没有重复(不包括我在列表中做出的故意重复,即:我想要一个包含2个c1,c2,c3等的16个项目的列表,但不是像3 c1,1 c2,5 c3那样的东西。
def random_assignment():
list_of_pairs = [c1, c1, c2, c2, c3, c3, c4, c4, c5, c5, c6, c6, c7, c7, c8, c8]
random_list = list(random.choice(list_of_pairs))
keep_generating = True
while keep_generating:
return random_list
if len(random_list) == 16:
keep_generating = False
from random import randint
list_of_pairs = [i for i in range(8)]*2
lista = []
for _ in list_of_pairs[:]:
lista.append(list_of_pairs.pop(randint(0,len(list_of_pairs)-1)))
当然,这也是不太“正确”的方式 - 这通常是不好的做法
[list_of_pairs.pop(randint(0,len(list_of_pairs)-1)) for _ in list_of_pairs[:]]
您可以使用随机模块中的shuffle函数来获取一组唯一的随机整数:
import random
my_list = list(xrange(1,100)) # list of integers from 1 to 99
# adjust this boundaries to fit your needs
random.shuffle(my_list)
print my_list # <- List of unique random numbers
请注意,shuffle方法不会像人们预期的那样返回任何列表,它只会随机引用传递的列表。