在确保没有重复项的同时,如何创建随机生成的项目列表?

时间:2018-09-15 21:47:47

标签: python-3.x list random

我正在尝试创建一个函数,该函数从列表中随机选择项目,并在每次运行时创建一个具有随机项目顺序的新列表。我相信我已经完成了很多工作,但是,我缺少一种方法来确保函数运行时,它始终只生成列表中每个项目中的一个而没有重复项(不包括我在列表中进行的故意重复,即:我想要一个包含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

2 个答案:

答案 0 :(得分:0)

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[:]]

答案 1 :(得分:-2)

您可以像这样使用随机模块中的随机播放功能来获取唯一的随机整数集:

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方法不会像预期的那样返回任何列表,它只会对通过引用传递的列表进行随机排序。