简体   繁体   English

基于列表python列表的第一个元素的平均值

[英]Average based on first element of list of lists python

Input is list of runs for a batsman.输入是击球手的跑位列表。 It should return country against which batsman has highest average of runs.它应该返回击球手平均得分最高的国家。

I am trying to find highest average so for example when below list is passed to my method it should return "Pakistan".我试图找到最高平均值,例如,当下面的列表传递给我的方法时,它应该返回“巴基斯坦”。

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

I have tried:我试过了:

create two dictionaries :创建两个字典:

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

thought of dividing values of two dicts and find highest of them.想到将两个字典的值相除并找到它们中的最高值。

Is there any other efficient way?有没有其他有效的方法?

Thanks for the help.谢谢您的帮助。

You can use pandas to achieve that, your code would be like:您可以使用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)

Print:打印:

['Pakistan', '77']

Probably could be done with fewer lines of code but this works!!可能可以用更少的代码行来完成,但这是有效的!!

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)

You can create a dictionary with country name as the key and a list of country-count and score as value.您可以创建一个以国家/地区名称为键,以国家/地区计数和分数列表为值的字典。 then you can further modify the same dictionary for calculating avg and use max to print the country with max avg.然后您可以进一步修改相同的字典来计算平均并使用 max 打印具有最大平均的国家。

here is the code:这是代码:

>>> 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)
>>> 

There could be easier and more pythonic way to do it but, this is where the logic lies.可能有更简单、更 Pythonic 的方法来做到这一点,但这就是逻辑所在。

Thia is an other way to do it: Thia 是另一种方法:

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)

Output: The highest average is Pakistan: 77输出: The highest average is Pakistan: 77

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM