【问题标题】:How do you create a randomly generated list of items while ensuring there are no duplicates?如何在确保没有重复项的同时创建随机生成的项目列表?
【发布时间】:2018-09-15 21:47:46
【问题描述】:

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

【问题讨论】:

  • 最后两行是不可理解的语句。
  • 格式错误,“数据”不清楚c1 等未知 - 代码抛出 NameError - 投票结束。

标签: python-3.x list random


【解决方案1】:
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[:]]

【讨论】:

    【解决方案2】:

    您可以像这样使用 random 模块中的 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 方法不会像预期的那样返回任何列表,它只会对通过引用传递的列表进行打乱。

    【讨论】:

    • 这不能回答 Salizmo 的问题!它被标记为 Python 3,但您的答案是 Python 2,并且您使用的列表与 Salizmo 的问题没有关系(名称或价值)...
    • 问题标记为python 3
    猜你喜欢
    • 2011-11-08
    • 2015-06-30
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    相关资源
    最近更新 更多