2017-09-17 18 views
-1

我想爲所有同名球員取平均值。我寫了下面的代碼。它顯示索引錯誤有什麼問題?如何通過將元組列表轉換爲字典來查找值的最大平均值?

輸入:l = [('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 122), ('Ashwin', 90)]

輸出:l = [('Kohli', 40), ('Ashwin', 61.5), ('Pujara', 122)]

t=0 
l2=[] 
for i in range(len(l)): 
    for j in range(len(l)): 
     if j < len(l) - 1 : 
      if l[i][0] == l[j][0]: 
        l2[t][0] = l[j][0] 
        l2[t][1] = (l[j][1] + l[j+1][1])/2 
        t = t + 1 
+0

什麼是't'和'l2'?我所能提供的所有東西都是名稱錯誤。 –

+0

t = 0 l2是空列表 –

回答

1

一種方式

from collections import defaultdict 
data_dict = defaultdict(list) 
l = [('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 122), ('Ashwin', 90)] 

for k, v in l: 
    data_dict[k].append(v) 
data_dict = dict(data_dict) 
# {'Pujara': [122], 'Ashwin': [33, 90], 'Kohli': [73, 7]} 

for k,v in data_dict.items(): 
    data_dict[k] = sum(v)/len(v) 

# {'Ashwin': 61.5, 'Kohli': 40.0, 'Pujara': 122.0} 

要將字典轉換成元組,你可以使用壓縮即

list(zip(data_dict.keys(),data_dict.values())) 

#[('Ashwin', 61.5), ('Pujara', 122.0), ('Kohli', 40.0)] 

要找到最大值的列表,你可以使用最大即

max(data_dict.values()) #122 

要獲得鑰匙,您可以使用

[i for i,j in data_dict.items() if j == max(data_dict.values())] # ['Pujara'] 
0

我不認爲你的算法可以正常工作,因爲abc平均爲(a+b+c)/3,不((a+b)/2+c)/2

你可以保持2 counters,一個用於OCCURENCES和一個分數:

l = [('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 122), 
    ('Ashwin', 90)] 

from collections import Counter 

counts = Counter() 
scores = Counter() 

for name, score in l: 
    counts[name] += 1 
    scores[name] += score 

print(counts) 
print(scores) 

它輸出:

Counter({'Kohli': 2, 'Ashwin': 2, 'Pujara': 1}) 
Counter({'Ashwin': 123, 'Pujara': 122, 'Kohli': 80}) 

應該不會太難遍歷scores現在計算平均值。默認字典的幫助下

0

這裏是不使用的集合庫

ip=[('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 122), 
('Ashwin', 90)] 

op=[] 
players=set() 

for item in ip: 
    x,y=item 
    players.add(x) 

for player in players: 
    sum_run=0 
    ctr=0 
    for i in ip: 
     if player in i: 
      x,y=i 
      sum_run=sum_run+y 
      ctr+=1 
     else: 
      pass 

    avg_run=sum_run/ctr 
    op_set = (player,avg_run) 
    op.append(op_set) 

print op 

解決它的輸出

[('Kohli', 40), ('Ashwin', 61), ('Pujara', 122)] 
+0

有沒有不使用'collections'的理由?一眼看你的代碼是關於'n ** 2'的,它更長,更不可讀 - 請參閱python的Zen。 –

相關問題