简体   繁体   English

从给定的元组列表中找到最大平均值

[英]finding the maxaverage from given list of tuples

Write a Python function maxaverage(l) that takes a list of pairs of the form (name,score) as argument, where name is a string and score is an integer. 编写一个Python函数maxaverage(l),该函数将一对形式为(name,score)的对的列表作为参数,其中name是一个字符串,score是一个整数。 Each pair is to be interpreted as the score of the named player. 每对将被解释为指定球员的得分。 For instance, an input of the form [('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',122),('Ashwin',90)] represents two scores of 73 and 7 for Kohli, two scores of 33 and 90 for Ashwin and one score of 122 for Pujara. 例如,格式为[[''Kohli',73),(''Ashwin',33),('Kohli',7),(''Pujara',122),('Ashwin',90)'的输入表示Kohli分别获得73分和7分,Ashwin获得2分33分和90分以及Pujara获得122分。 Your function should compute the players who have the highest average score (average = total across all scores for that player divided by number of entries) and return the list of names of these players as a list, sorted in alphabetical order. 您的函数应该计算平均得分最高的球员(平均值=该球员所有得分的总和除以参赛人数),然后以字母顺序返回这些球员的姓名列表作为列表。 If there is a single player, the list will contain a single name. 如果只有一个玩家,则列表将包含一个名称。

For instance, maxaverage([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',122),('Ashwin',90)]) should return ['Pujara'] because the average score of Kolhi is 40 (80 divided by 2), of Ashwin is 61.5 (123 divided by 2) and of Pujara is 122 (122 divided by 1), of which 122 is the highest. 例如, maxaverage([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',122),('Ashwin',90)])应该返回[ 'Pujara'],因为Kolhi的平均得分为40(80除以2),Ashwin的平均得分为61.5(123除以2),Pujara的平均得分为122(122除以1),其中122为最高。

In the same way the solution should be ['Kohli', 'Ashwin'] if l = ([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara'‌​,22),('Ashwin',47)]) but I'm getting only kohli 同样['Kohli', 'Ashwin']如果l = ([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara'‌​,22),('Ashwin',47)])则解决方案应为['Kohli', 'Ashwin'] l = ([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara'‌​,22),('Ashwin',47)])但我只得到kohli

from collections import defaultdict

def maxaverage(l):
    dl = []
    data_dict = defaultdict(list)
    for k, v in l:
        data_dict[k].append(v)
    data_dict = dict(data_dict)

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

    list(zip(data_dict.keys(), data_dict.values()))
    max(data_dict.values())
    x = (max(data_dict, key=data_dict.get))
    dl.append(x)
    return dl

Try these codes: 尝试以下代码:

l = [('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 22), ('Ashwin', 47)]


def max_average(l):
    from operator import itemgetter
    from itertools import groupby
    lst_of_pairs = list()

    for key, group in groupby(sorted(l, key=itemgetter(0)), key=itemgetter(0)):
        scores = list(x[1] for x in group)
        avg = sum(scores) / len(scores)
        lst_of_pairs.append((key, avg))

        lst_of_pairs.sort(key=itemgetter(1), reverse=True)
    max_avg = lst_of_pairs[0][1]
    return list(e[0] for e in filter(lambda x: x[1] == max_avg, lst_of_pairs))


print(max_average(l))

And for the case in 'l', you can get ['Ashwin', 'Kohli'] as expected. 对于'l'的情况,您可以按预期获得['Ashwin','Kohli']。 Remeber that the groupby will only work on a sorted lists. 请记住,groupby仅适用于排序列表。

Just add a list comprehension at the end of the method to get the keys of dict based on max average ie 只需在方法末尾添加列表推导,即可基于最大平均值获得字典键,即

from collections import defaultdict

def maxaverage(l):
    data_dict = defaultdict(list)

    for k, v in l:
        data_dict[k].append(v)

    data_dict = dict(data_dict)

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

    dl = [i for i,j in data_dict.items() if j == max(data_dict.values())]
    return dl 

Output: 输出:

maxaverage([('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 22), ('Ashwin', 47)])
#['Ashwin', 'Kohli']

maxaverage(([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',122),('Ashwin',90)]) 
#['Pujara']

Here is a corrected version of your code that ensures that the final result is sorted alphabetically. 这是代码的更正版本,可确保最终结果按字母顺序排序。 It also has some efficiency improvements: 它还提高了一些效率:

from collections import defaultdict

def maxaverage(l):
    data_dict = defaultdict(list)
    for k, v in l:
        data_dict[k].append(v)

    data_dict = {k: sum(v)/len(v) for k,v in data_dict.items()}

    max_avg = max(data_dict.values())
    return sorted([k for k in data_dict if data_dict[k] == max_avg])


>>> maxaverage(([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',122),('Ashwin',90)]))
['Pujara']

>>> maxaverage([('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 22), ('Ashwin', 47)])
['Ashwin', 'Kohli']

Note that the solution in the 2nd test case should be ['Ashwin', 'Kohli'] , not ['Kohli', 'Ashwin'] (as stated in your question) because the final list should be sorted. 请注意,第二个测试用例中的解决方案应该是['Ashwin', 'Kohli'] ,而不是['Kohli', 'Ashwin'] (如您的问题所述),因为最终列表应进行排序。

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

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