Python 程序实现循环赛
我正在写一个程序,允许用户输入一个偶数的玩家数量,然后它会生成一个循环赛程安排。总共会有 n/2 * n-1
场比赛,这样每个玩家都会和其他每个玩家比赛。
现在我在生成用户输入的玩家数量列表时遇到了困难。我得到了这个错误:
TypeError: 'int' object not iterable.
我在程序中经常遇到这个错误,所以我想我可能对Python的这一部分理解得不太好。如果有人能帮我解释一下,我会很感激。
def rounds(players, player_list):
"""determines how many rounds and who plays who in each round"""
num_games = int((players/2) * (players-1))
num_rounds = int(players/2)
player_list = list(players)
return player_list
2 个回答
4
player_list= list(players)
这是导致出现 TypeError
的原因。这个错误发生是因为 list()
函数只能处理那些可以被遍历的对象,而 int
(整数)并不是这样的对象。
从评论来看,你似乎只是想创建一个包含玩家编号(或者名字、或者索引)的列表。你可以这样做:
# this will create the list [1,2,3,...players]:
player_list = range(1, players+1)
# or, the list [0,1,...players-1]:
player_list = range(players) # this is equivalent to range(0,players)
6
如果你只是想得到一串数字,你可能需要用到 range()
这个函数。
如果你想要进行真正的循环赛(round-robin tournament),那你应该看看 itertools.combinations
。
>>> n = 4
>>> players = range(1,n+1)
>>> players
[1, 2, 3, 4]
>>> list(itertools.combinations(players, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]