2017-04-20 43 views
0

我正在嘗試創建一個程序,以便將數值分數從最高到最低排列。確定等級中的關係

for i in scores: 
    if i[1] == max_score: 
     print 'rank ', ctr,'highest score: {} of {}'.format(i[1], i[0]) 
     pass 

    if i[1] not in [max_score, min_score]: 
     ctr= ctr+1 
     print'rank ', ctr,'score: {} of {}'.format(i[1], i[0]) 
     pass 



    if i[1] == min_score: 
     ctr= ctr+1 
     print 'rank ',ctr,'lowest score: {} of {}'.format(i[1], i[0]) 

文本文件包含:

john = 10 
johnny=10 
joseph = 9 
j=9 
jose = 8 
q=7 

然而,我的代碼的輸出是:

rank 1 highest score: 10.0 of john 
rank 1 highest score: 10.0 of johnny 
rank 2 score: 9.0 of joseph 
rank 3 score: 9.0 of j 
rank 4 score: 8.0 of jose 
rank 5 lowest score: 7.0 of q 
+0

在行'ctr = ctr + 1'中,您只需增加每個位置。你從不檢查分數是否與之前的分數相符。 –

+0

感謝您的幫助,你能給我一個指導如何檢查以前的分數,如果你不介意?非常感謝你 –

回答

0

這是我會怎麼做:

ordered_score_values = sorted(set([s[1] for s in scores]), reverse=True) 
for i in scores: 
    ctr = (ordered_score_values.index(i[1])) + 1 
    if i[1] == max_score: 
     print 'rank ', ctr, 'highest score: {} of {}'.format(i[1], i[0]) 

    if i[1] not in [max_score, min_score]: 
     print 'rank ', ctr, 'score: {} of {}'.format(i[1], i[0]) 

    if i[1] == min_score: 
     print 'rank ', ctr, 'lowest score: {} of {}'.format(i[1], i[0]) 

的變量ordered_score_values爲你的示例將包含[10, 9, 8, 7]。原因如下:set消除重複。 sorted將它們按順序排列,並且reverse確定該順序是從高到低。

每個人的排名計算以同樣的方式;我們添加+ 1,因爲該列表是零索引的,但您寧願從1開始計數。

+0

非常感謝你:)你真棒:) –

+0

從我的答案中有什麼缺失導致你不接受它嗎? –

+0

theres沒有錯你的答案是非常正確的謝謝你很多偉大的:) –

0

雖然答案已被接受,但我想使用您的給定代碼提供一種方式。每次通過第二個if語句時,您的代碼都會更新ctr,這就是爲什麼它會繼續計數。您需要一種方法來檢查該分數是否等於另一個分數。

添加一個幫助變量(我用x)並給它一個0值。在你的第二個if語句中,添加另一個if語句來檢查我是否小於x。如果是這樣,請向ctr添加1。最後,在你的循環中,將x值設置爲i [1]。

scores={} 
ctr=1 
ctr1=2 
ctr3=3 

files=open("test.txt","r").readlines() 
scores = [i.split('=') for i in files] 
scores = [[i[0], float(i[1])] for i in scores] 
scores = sorted(scores, key=lambda x: -x[1]) 

print scores 
max_score = max([i[1] for i in scores]) 
min_score = min([i[1] for i in scores]) 

x = 0 
for i in scores: 
    if i[1] == max_score: 
     print 'rank ', ctr,'highest score: {} of {}'.format(i[1], i[0]) 
     pass 

    if i[1] not in [max_score, min_score]: 
     if i[1] < x: 
      ctr = ctr + 1 
     print'rank ', ctr,'score: {} of {}'.format(i[1], i[0]) 
     pass 



    if i[1] == min_score: 
     ctr= ctr+1 
     print 'rank ',ctr,'lowest score: {} of {}'.format(i[1], i[0]) 
    x = i[1] 

這將根據您的腳本執行您想要的操作,但確實有更有效的方法來執行此操作。

+0

非常感謝你:) –