开发者社区> 问答> 正文

如何列出随机唯一元组?

我已经查看了几个与该问题类似的答案,并且所有答案似乎都具有很好的oneliner答案,但是仅解决了通过删除重复项使列表唯一的事实。我需要清单精确地有5个。

我唯一能想到的代码是这样的:

from random import \*        
tuples = []

while len(tuples) < 5:
    rand = (randint(0, 6), randint(0,6))
    if rand not in tuples:
        tuples.append(rand)

我觉得有一种更简单的方法,但我不知道。我尝试从随机玩sample():

sample((randint(0,6), randint(0,6)), 5)

但这给了我一个“样本大于总体或为负”的错误。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 20:29:39 371 0
1 条回答
写回答
取消 提交回答
  • 一种快速的方法是使用itertools.product生成所有元组可能性,然后再使用sample从中选择5种可能性:

    from itertools import product
    from random import sample
    sample(list(product(range(7), repeat=2)), k=5)
    

    回答来源:stackoverflow

    2020-03-24 20:29:45
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载