3

我正在编写一个程序,允许用户输入偶数个玩家,然后它将生成一个循环锦标赛时间表。n/2 * n-1游戏的数量,以便每个玩家都玩其他玩家。

现在我很难生成用户输入的玩家数量列表。我收到此错误:

TypeError:'int' 对象不可迭代。

我在我的程序中经常遇到这个错误,所以我想我不太了解 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
4

2 回答 2

6

如果您只想获取数字列表,则可能需要该range()功能。

对于实际的循环赛,您应该查看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)]
于 2013-03-12T04:01:59.347 回答
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)
于 2013-03-12T04:04:33.013 回答