0

我使用 Python 2.6。

我的代码可以在这里编辑和运行:http: //www.codeskulptor.org/#user12_OQL53Z5Es8yDHRB.py

# set the arguments
teams = 4
rounds = 2 * (teams - 1)

# show the arguments
print teams, "teams"
print rounds, "rounds"

# season is a list of lists
# each sub list is a round
season = rounds*["round"]

# store the first round in season[0]
round = range(1, teams + 1)
season[0] = round[:]

# store the other rounds in season
for j in range(1, rounds):
    round2 = round[:]
    round2[1] = round[teams - 1]
    for i in range(2, teams):
        round2[i] = round[i - 1]
    season[j] = round2[:] 
    round = round2

# print the season    
print season

如果有 4 支球队并且每个人每支球队打两次,我想要这个最终结果:[1,2,3,4],[1,4,2,3],[1,3,4,2],[1, 2、3、4]、[1、4、2、3]、[1、3、4、2]]。第 1 队留在原地,其他队轮换。每个团队向右移动一个位置,除了团队 1 和列表中最后一个移动到团队 1 旁边的位置的团队。

我相信上面的代码有效。我是 Python 的新手,所以我正在寻找更好或更优雅的代码。

谢谢!

4

2 回答 2

1

更易读的版本:

[...]

first_round = range(1, teams + 1)
season = [first_round]

def rotate(round):
    return [round[0], round[-1]] + round[1:-1]

for i in range(0, rounds - 1):
    previous_round = season[i]
    season.append(rotate(previous_round))

print season
于 2013-05-09T09:57:27.197 回答
1

您可以使用itertools.permutations来创建所有排列,然后选择以 1 开头的第一组:

from itertools import permutations
from math import factorial

season = list(permutations(range(1, teams+1)))[:factorial(teams)/teams]

或者在不生成所有排列的情况下,获取 2 到 4 的排列,然后附加到 1:

season = [[1] + list(i) for i in permutations(range(2, teams+1))]
于 2013-05-09T09:57:49.497 回答