2013-03-29 60 views
3

我正在研究一個生成單一淘汰賽的程序。到目前爲止我的代碼看起來像這樣(我剛剛開始)從python列表中選擇數字

amount = int(raw_input("How many teams are playing in this tournament? ")) 
teams = [] 
i = 0 
while i<amount: 
    teams.append(raw_input("please enter team name: ")) 
    i= i+1 

現在我卡住了。我想隨機挑選2個數字來選擇面對海誓山盟的球隊。這些數字根本無法重複,並且必須從1到「數量」。什麼是最有效的方法來做到這一點?

回答

11

看看random模塊。

>>> import random 
>>> teams = ['One team', 'Another team', 'A third team'] 
>>> team1, team2 = random.sample(teams, 2) 
>>> print team1 
'Another team' 
>>> print team2 
'One team' 
+1

不錯!我檢查了文檔,'random.sample()'將返回列表中的兩個唯一值。因此,只要每個隊名都在列表中,這就保證隨機選擇兩個不同的隊名。我認爲沒有比這更好的解決方案! – steveha

+1

謝謝,這是完美的! – chadybear

+0

@ user2108568不客氣:)。不要忘記接受答案:)。 – TerryA

2
team1 = random.choice(teams) 
teams.remove(team1) 
team2 = random.choice(teams) 

我認爲應該工作。

+0

是的。在Python中,您可以詢問您真正想要的內容:隨機選擇一個團隊。不需要獲得一個隨機數字並使用它來獲得團隊,只需要隨機選擇一個團隊。 – steveha

+0

這取決於你需要的東西:這是一種從大於2的列表中選擇2個團隊的方法。如果你將有一個團隊遺留下來,你將不得不爲他們做一個特例(不管你使用什麼方法來配對隊伍,給他們一個再見或者什麼)。 –

0

我不能完全肯定,但是你問什麼選擇,你可以使用例如隨機數

random.randint(1,10) 

這會給你1到10中

注隨機號碼:您需要導入隨機模塊

import random