2013-03-12 78 views
3

我正在編寫一個程序,允許用戶輸入甚至是數字,然後它會生成一個循環賽比賽時間表。 n/2 * n-1遊戲數量,以便每個玩家玩其他玩家。循環賽比賽的python程序

現在我很難生成用戶輸入的玩家數量列表。我得到這個錯誤:

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 
+0

你打電話給'rounds'? – Blender 2013-03-12 03:58:16

+0

你打算用'list(players)'做什麼? – pradyunsg 2013-03-12 03:59:24

+0

有多少遊戲可以在同一時間進行,因此n/2 – tinydancer9454 2013-03-12 03:59:24

回答

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)] 
+0

這確實幫助我生成了列表,但它包含了0.我現在有:player_list = list(range(players))我如何以1開頭?我確定這很容易,但是我對列表很陌生,我不確定 – tinydancer9454 2013-03-12 04:03:32

+0

'range(x,y)'產生一個從'x'到'y-1'的數字範圍(而'range(y )'產生從'0'到'y-1'的一系列數字)。 – Amber 2013-03-12 04:05:27

+0

它說全局名稱itertools沒有定義 – tinydancer9454 2013-03-12 19:23:04

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)