2016-02-21 110 views
1

輸入是擊球手運行列表。它應該返回擊球手跑平均得分最高的國家。基於列表的第一個元素的平均值python

我想找到最高的平均值,例如當下面的列表傳遞給我的方法時,它應該返回「巴基斯坦」。

[ 
["Pakistan", 23], 
["Pakistan", 127], 
["India", 3], 
["India", 71], 
["Australia", 31], 
["India", 22], 
["Pakistan", 81] 
] 

我曾嘗試:

創建兩個庫:將2類型的字典值的

total={'Australia': 31, 'India': 96, 'Pakistan': 231} 
division={'Australia': 1, 'India': 2, 'Pakistan': 3} 

思想,找到他們最高的。

還有其他有效的方法嗎?

感謝您的幫助。

回答

1

大概可以用更少的代碼來完成,但這作品!

def average(data): 
    highest = {} 
    index = 0 
    while True: 
     for i in data: 
      if i[0] in highest: 
       highest[i[0]].append(i[1]) 
      else: 
       highest[i[0]] = [i[1]] 
     for i in highest: 
      highest[i] = sum(highest[i])/len(highest[i]) 
     answer = 0 
     for i in highest: 
      if highest[i] >= answer: 
       answer = i 
     return answer 
print average(data) 
2

您可以使用pandas實現這一目標,你的代碼將是這樣的:

import pandas as pd 
data = [ 
    ["Pakistan", 23], 
    ["Pakistan", 127], 
    ["India", 3], 
    ["India", 71], 
    ["Australia", 31], 
    ["India", 22], 
    ["Pakistan", 81] 
] 
df = pd.DataFrame(data, columns=['country', 'count']) 
grouped = df.groupby(['country']).mean().reset_index() 
highest = list(grouped.max()) 
print(highest) 

打印:

['Pakistan', '77'] 
1

您可以創建一個國家名稱作爲關鍵字和國家數量和分數列表作爲值的字典。那麼您可以進一步修改相同的詞典以計算平均值,並使用max以max avg打印國家。

這裏是代碼:

>>> a = [ 
["Pakistan", 23], 
["Pakistan", 127], 
["India", 3], 
["India", 71], 
["Australia", 31], 
["India", 22], 
["Pakistan", 81] 
] 
>>> 
>>> 
>>> a 
[['Pakistan', 23], ['Pakistan', 127], ['India', 3], ['India', 71],   ['Australia', 31], ['India', 22], ['Pakistan', 81]] 
>>> d = {} 
>>> for l in a: 
     if l[0] not in d.keys(): 
      d.update({l[0]:[1,l[1]]}) 
     else: 
      d[l[0]] = [d[l[0]][0]+1,d[l[0]][1]+l[1]] 


>>> #updated list 
>>> d 
{'Pakistan': [3, 231], 'Australia': [1, 31], 'India': [3, 96]} 
>>> for key,val in d.items(): 
d[key] = val[1]/val[0] 

#Updated dict with average per country 
>>> d 
{'Pakistan': 77.0, 'Australia': 31.0, 'India': 32.0} 

>>> max(d.items()) 
('Pakistan', 77.0) 
>>> 

有可能是更容易,更Python的方式做到這一點,但是,這是那裏的邏輯所在。

1

硫雜是其他的方式來做到這一點:

lst = [ 
["Pakistan", 23], 
["Pakistan", 127], 
["India", 3], 
["India", 71], 
["Australia", 31], 
["India", 22], 
["Pakistan", 81] 
] 
tuples = [tuple(i) for i in lst] 
newdata = {} 
for k,v in tuples: 
    newdata.setdefault(k, []).append(v) 
result = {k:(sum(v)/len(v)) for k,v in newdata.items()} 
a = max(result) 
b = max(result.values()) 
print "The highest average is %s: %s " % (a,b) 

輸出: The highest average is Pakistan: 77

相關問題