输入是击球手的运行列表。它应该返回击球手平均得分最高的国家。
我正试图找到最高的平均值,因此,例如,当下面的列表被传递给我的方法时,它应该返回“巴基斯坦”。
[
["Pakistan", 23],
["Pakistan", 127],
["India", 3],
["India", 71],
["Australia", 31],
["India", 22],
["Pakistan", 81]
]我试过:
创建两个字典:
total={'Australia': 31, 'India': 96, 'Pakistan': 231}
division={'Australia': 1, 'India': 2, 'Pakistan': 3} 想把两块分值分开,找出其中最高的值。
还有其他有效的方法吗?
谢谢你的帮助。
发布于 2016-02-21 07:59:14
也许可以用较少的代码行来完成,但这是可行的!!
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)发布于 2016-02-21 07:53:38
您可以使用熊猫来实现这一点,您的代码如下:
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']发布于 2016-02-21 08:09:22
您可以创建一个以国家名称为键的字典,以及一个国家计数和分数作为值的列表。然后,您可以进一步修改用于计算avg的同一词典,并使用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)
>>> 可以有更简单、更复杂的方法来做这件事,但这是逻辑所在。
https://stackoverflow.com/questions/35533477
复制相似问题