2012-03-25 48 views
1

所以我試圖做一個代碼來計算測驗中兩個玩家之間的分數差異。有第一輪比分和第二輪比分。如何將輸出中的列表中的兩個元素配對?

這是我到目前爲止有:

import math 

option = input ('How many players?: ') 

playerlist = [] 
firstroundlist = [] 
secondroundlist = [] 

j = 0 
while j < option: 
    name = raw_input('Enter player\'s name: ') 
    playerlist.append(name,) 

    firstround = input ('Enter first round score: ') 
    firstroundlist.append(firstround,) 

    secondround = input('Enter second round score: ') 
    secondroundlist.append(secondround,) 

    j += 1 

y=0 
z=1 
dis=[] 
while z<len(playerlist): 
    comparison = (firstroundlist[y]+secondroundlist[y])-(firstroundlist[z]+secondroundlist[z]) 
    print playerlist[y], '-', playerlist [z], 'is', comparison 
    z+=1 

z==0 
y+=1 

但是,讓我們說,我輸入了四種不同的球員得分,輸出此代碼會是這樣的:

Player 1 - Player 2 is #scoredifference 
Player 1 - Player 3 is #scoredifference 
Player 1 - Player 4 is #scoredifference 

的問題是,我該如何修改代碼,以便它會是這樣的:

Player 1 - Player 2 is #scoredifference 
Player 1 - Player 3 is #scoredifference 
Player 1 - Player 4 is #scoredifference 
Player 2 - Player 3 is #scoredifference 
Player 2 - Player 4 is #scoredifference 
Player 3 - Player 4 is #scoredifference 
+0

備註:請勿使用while循環。在範圍(選項)中使用':j替代('range(1,len(playerlist))'爲第二個循環)。 – 2012-03-25 02:40:52

回答

1
for i in range(len(playerlist)): 
    for j in range(i+1, len(playerlist)): 
     print "player %d - player %d is %d", (i, j, scoredifference[i,j]) 

應該爲你做詭計。顯然,更換scoredifference用正確的公式..

+1

這將比較3-3。另外,我認爲一個嵌套的'range(len())'實際上是非空調的。 – phihag 2012-03-25 02:50:34

+0

感謝您抓住我的錯誤! – 2012-03-25 03:21:36

+0

@KurtSpindler謝謝!順便說一句,你有什麼想法,我怎麼能打印所有分數差異的平均值? – DarsAE 2012-03-25 06:57:27

3

您正在尋找itertools.combinations

import itertools 
for y,z in itertools.combinations(range(len(playerlist)), 2): 
    comparison = (firstroundlist[y]+secondroundlist[y])-(firstroundlist[z]+secondroundlist[z]) 
    print (playerlist[y] + '-' + playerlist[z] + 'is' + str(comparison)) 

請注意,您的數據結構是不是最佳的。您應該使用的玩家信息tuples,像這樣:

import itertools 
playernum = int(raw_input('How many players?: ')) 
players = [(
    raw_input('Enter player\'s name: '), 
    int(raw_input('Enter first round score: ')), 
    int(raw_input('Enter second round score: ')), 
) for i in range(playernum)] 

for p,q in itertools.combinations(players, 2): 
    comparison = (p[1]+p[2])-(q[1]+q[2]) 
    print (p[0] + '-' + q[0] + 'is' + str(comparison)) 

順便說一句,你目前的代碼中包含語法錯誤。取而代之的

name = raw_input('Enter player's name: ') 

你想:

name = raw_input('Enter player\'s name: ') 

另外,代替input()(其中執行任意Python代碼!)你想int(raw_input())

+0

謝謝! 但我得到這個錯誤:9號線,在 爲P,在itertools.combinations(玩家)問: 類型錯誤:必需的參數 'R'(POS 2)未找到 是什麼意思? – DarsAE 2012-03-25 03:40:32

+0

哎呀,對不起,我的錯誤 - 我忽略了我想要的組合數量。用',2'更新了答案。 – phihag 2012-03-25 03:47:07

相關問題