【问题标题】:How can one generate all possible teams of players from a list?如何从一个列表中生成所有可能的球员球队?
【发布时间】:2020-01-15 15:11:51
【问题描述】:

我有一个名单,比如说,3 名玩家:

[1, 2, 3]

如何在 python 中生成列表列表,格式为:

[[1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]

代表所有可以与上述球员组成的球队?

【问题讨论】:

标签: python python-3.x numpy


【解决方案1】:

您可以使用itertools.combinations(),我们可以将r 参数设置为从1 到列表长度(x) 的所有长度,以获取所有可能在列表理解中被展平的组合。

from itertools import combinations

x = [1, 2, 3]
result = [c for i in range(1, len(x)+1) for c in combinations(x, i)]
print(result)  # -> [(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

【讨论】:

    【解决方案2】:

    使用https://docs.python.org/3/library/itertools.html#itertools.combinations

    它完全符合您的要求。

    import itertools
    players = [1, 2, 3]
    print(list(itertools.chain.from_iterable(itertools.combinations(players, r) for r in range(1, len(players) + 1))))
    

    输出:

    [(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
    

    由于使用了 itertools.chain,这可能是最有效的答案

    【讨论】:

      【解决方案3】:

      您可以使用具有给定尺寸的itertools.combinations 来生成固定尺寸组合。为了概括,您可以在所有尺寸上使用 for 循环。代码如下所示:

      import itertools
      
      my_list = [1, 2, 3]
      for L in range(0, len(my_list)+1):
          for subset in itertools.combinations(my_list, L):
              print(subset)
      

      【讨论】:

      • 那是相当低效的。如果您的团队规模非常大,您应该使用 itertools.chain 使用 C 扩展对其进行优化
      • 如果问题要求性能,显然有更好的选择。您也可以将 Cython 加入其中,尝试使用 NumPy 和 Numba 加速或使用 dash 并行化。我的意思是,没有这样的要求。程序员的时间可能比 CPU 时间更昂贵,因此您需要一个理由来使事情复杂化。
      • 但是更快的方法编码也更快;它只有 1 行处理
      【解决方案4】:

      Itertools 是这些操作的朋友:

      import itertools
      
      l = [1, 2, 3]
      
      l = [list(x) for y in range(1,len(l)+1) for x in itertools.combinations(l,y) ]
      print(l)
      

      给予:

      [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
      

      【讨论】:

        【解决方案5】:

        您可以使用itertools。您要做的是生成给定列表的 powerset。

        >>> import itertools
        >>> a=[1,2,3]
        >>> out=[]
        >>> for i in range(len(a)+1):
            out+=list(itertools.combinations(a,i))
        
        
        >>> out
        [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
        >>> 
        

        您可以编写recursive函数来生成powerset,如下所示:

        >>> def powerset(s,idx,curr,out):
            if idx==len(s):
                out.append(curr)
                return
            (powerset(s,idx+1,curr+[s[idx]],out))
            (powerset(s,idx+1,curr,out))
            return sorted(out,key=lambda x:len(x))
        
        >>> z=powerset(a,0,[],[])
        >>> z
        [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
        

        【讨论】:

          猜你喜欢
          • 2016-03-18
          • 1970-01-01
          • 2021-01-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-22
          • 1970-01-01
          相关资源
          最近更新 更多