【问题标题】:Random pairs without repeats in Python (numpy or itertools)Python 中没有重复的随机对(numpy 或 itertools)
【发布时间】:2021-03-11 17:59:57
【问题描述】:

我有一个人员列表,并希望生成一些随机配对或三胞胎,以便列表中的每个人都恰好属于一对或三胞胎(不多也不少)。

例子:

>>> people = ["John", "Paul", "George", "Ringo", "David", "Roger", "Richard", "Nick", "Syd"]

>>> generate_random_pairs(people)

[
    ("John", "George"),
    ("Paul", "David"),
    ("Roger", "Nick"),
    ("Ringo", "Richard", "Syd")
]

我使用numpy.random.choicenumpy.random.sampleitertools.permutations 尝试了不同的想法,但它们似乎都不起作用。

【问题讨论】:

  • 请分享一些尝试,以便我们看到您做了一些努力,而不仅仅是请求代码;)
  • 随机播放,然后切成适当大小的块?
  • @azro 这可能会污染问题并使其不那么简洁;)
  • @jonrsharpe 不管你是谁,我欠你一杯啤酒

标签: python numpy random itertools sample


【解决方案1】:

基于 jonrsharpe 的评论

import numpy as np

people = ["John", "Paul", "George", "Ringo", "David", "Roger", "Richard", "Nick", "Syd"]

shuffled = np.random.permutation(people)

pairs_or_triplets = [list(a) for a in np.array_split(shuffled, len(shuffled) / 2)]

【讨论】:

    【解决方案2】:

    使用grouper() recipe from itertools

    from itertools import zip_longest
    from random import shuffle
    
    def grouper(iterable, n, fillvalue=None):
        "Collect data into fixed-length chunks or blocks of size n."
        # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
        args = [iter(iterable)] * n
        return zip_longest(*args, fillvalue=fillvalue)
    
    people = ["John", "Paul", "George", "Ringo", "David", "Roger", "Richard", "Nick", "Syd"]
    
    shuffle(people)
    
    list(grouper(people, 3, ''))
    

    示例输出:

    [('Ringo', 'George', 'Syd'),
     ('Richard', 'David', 'John'),
     ('Paul', 'Roger', 'Nick')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-08
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 2023-03-19
      相关资源
      最近更新 更多