【问题标题】:intertools combination 2 vs 2 in a list python列表python中的itertools组合2 vs 2
【发布时间】:2020-04-02 17:45:05
【问题描述】:

我需要创建 2v2 人的团队

这是我的球员名单

L=["P1","P2","P3","P4"]

import itertools

我知道可以使用

创建所有 1v11v1v1
>>> L=["P1","P2","P3","P4"]
>>> for p in itertools.combinations(L,2) :
...     print(p)
... 
('P1', 'P2')
('P1', 'P3')
('P1', 'P4')
('P2', 'P3')
('P2', 'P4')
('P3', 'P4')

>>> for p in itertools.combinations(L,3) :
...     print(p)
... 
('P1', 'P2', 'P3')
('P1', 'P2', 'P4')
('P1', 'P3', 'P4')
('P2', 'P3', 'P4')

但是如何打印所有可能的 2V2 呢?

【问题讨论】:

  • 2v2是什么意思?
  • 我想要所有可能的组合来创建 match 2 vs2 。示例:P1&P2 vs P3&P4,P2&P3 vs P4&P1 等
  • 告诉我们您的预期输出
  • 嗯,我不知道确切的输出,这就是我需要一个代码的原因..
  • 不确定是否可以直接使用 itertools。

标签: python combinations itertools


【解决方案1】:

你可以做以下事情,虽然很天真但很有效:

for p in itertools.combinations(L,2) :
    o = tuple(x for x in L if x not in p)
    print(p, o)

('P1', 'P2') ('P3', 'P4')
('P1', 'P3') ('P2', 'P4')
('P1', 'P4') ('P2', 'P3')
('P2', 'P3') ('P1', 'P4')
('P2', 'P4') ('P1', 'P3')
('P3', 'P4') ('P1', 'P2')

对于更多玩家,你可以这样做:

L = ["P1", "P2", "P3", "P4", "P5"]
for p in itertools.combinations(L,2) :
    o = [x for x in L if x not in p]
    for x in itertools.combinations(o, 2):
        print(p, x)

你会给哪个双循环赛;) 对于单循环:

for p in itertools.combinations(L,2) :
    o = [x for x in L if x > p[0] and x != p[1]]
    for x in itertools.combinations(o, 2):
        print(p, x)

('P1', 'P2') ('P3', 'P4')
('P1', 'P2') ('P3', 'P5')
('P1', 'P2') ('P4', 'P5')
('P1', 'P3') ('P2', 'P4')
('P1', 'P3') ('P2', 'P5')
('P1', 'P3') ('P4', 'P5')
('P1', 'P4') ('P2', 'P3')
('P1', 'P4') ('P2', 'P5')
('P1', 'P4') ('P3', 'P5')
('P1', 'P5') ('P2', 'P3')
('P1', 'P5') ('P2', 'P4')
('P1', 'P5') ('P3', 'P4')
('P2', 'P3') ('P4', 'P5')
('P2', 'P4') ('P3', 'P5')
('P2', 'P5') ('P3', 'P4')

【讨论】:

  • 好的,如果现在我有一个包含 5 个玩家的列表呢?
  • @Grendel 只需遍历combinations(o, 2)o 的更好名称是 remaining,或者我认为它代表的名称 other
  • @Grendel 所以,顺序无关紧要,例如('P1', 'P2') ('P3', 'P4')('P3', 'P4') ('P1', 'P2') 不一样?
  • heu 是的,确实是一样的
  • 添加了单轮循环变种,没有重复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-28
  • 2012-07-09
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
相关资源
最近更新 更多