为循环赛锦标赛分组列表组合

时间:2015-09-02 16:51:42

标签: python list combinations itertools

编辑:我的问题不是重复,因为有人标记了。另一个问题是不正确的,甚至不起作用。

我尝试了几种方法来对itertools.combinations的结果进行分组,但无法提供正确的输出。需要在游戏中创建匹配。每个团队都需要每天都玩,但只需要一次。在接下来的几天里,球队需要扮演不同的球队,直到每个人都在为每个人打球。

for (var property in obj) {
  cities.push({value: property, text: obj[property]});
}

结果:

teams = [team 1, team 2, team 3, team 4]
print list(itertools.combinations(teams, 2))

但我需要的是将它们分组而不会有任何重复的列表项。 例如:

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

任何提示都会受到赞赏,我觉得可能有一个简单的单行程来完成这项任务。

1 个答案:

答案 0 :(得分:4)

基于链接问题中的Scheduling_algorithm使用collections.deque的实现:

from collections import deque
from itertools import islice

def fixtures(teams):
    if len(teams) % 2:
        teams.append("Bye")

    ln = len(teams) // 2
    dq1, dq2 = deque(islice(teams, None, ln)), deque(islice(teams, ln, None))
    for _ in range(len(teams)-1):
        yield zip(dq1, dq2) # list(zip.. python3
        #  pop off first deque's left element to 
        # "fix one of the competitors in the first column"
        start = dq1.popleft() 
        # rotate the others clockwise one position
        # by swapping elements 
        dq1.appendleft(dq2.popleft())
        dq2.append(dq1.pop())
        # reattach first competitor
        dq1.appendleft(start)

输出:

In [37]: teams = ["team1", "team2", "team3", "team4"]

In [38]: list(fixtures(teams))
Out[38]: 
[[('team1', 'team3'), ('team2', 'team4')],
 [('team1', 'team4'), ('team3', 'team2')],
 [('team1', 'team2'), ('team4', 'team3')]]

In [39]: teams = ["team1", "team2", "team3", "team4","team5"]

In [40]: list(fixtures(teams))
Out[40]: 
[[('team1', 'team4'), ('team2', 'team5'), ('team3', 'Bye')],
 [('team1', 'team5'), ('team4', 'Bye'), ('team2', 'team3')],
 [('team1', 'Bye'), ('team5', 'team3'), ('team4', 'team2')],
 [('team1', 'team3'), ('Bye', 'team2'), ('team5', 'team4')],
 [('team1', 'team2'), ('team3', 'team4'), ('Bye', 'team5')]]