有序字典Sum和排序前三的有序字典总和

时间:2016-03-28 12:02:48

标签: python python-2.7

根据this question的答案,我想在OrderedDict内对值进行求和:

names = OrderedDict([('Competitor Number', int),
        ('Competitor Name', str),
        ('Cucumber', to_inch),
        ('Carrot', to_inch),
        ('Runner Bean', to_inch)])

如何将黄瓜,胡萝卜和亚麻豆的价值加在一起?

to_inch只是一英寸到几英寸的转换。

以下是该区域周围的整个代码,其中包含订单dict和要从文件中读取的代码:

data = []
names = OrderedDict([('Competitor Number', int),
    ('Competitor Name', str),
    ('Cucumber', to_inch),
    ('Carrot', to_inch),
    ('Runner Bean', to_inch)])

with open('veggies_2015.dat') as fobj:
    while True:
        item = {}
        try:
            for name, func in names.items():
                item[name] = func(next(fobj).strip())
            data.append(item)
        except StopIteration:
            break
sorted_data = sorted(data, key=itemgetter('Runner Bean'), reverse = True)
for entry in sorted_data[:3]:
    for key, value in entry.items():
        print value
    print

我尝试过使用此解决方案,但没有成功sum(item['Competitor Name'] for item in data)

我目前可以得到前三名的结果,但它是基于这个实例Runner Bean的结果之一,但它应该基于黄瓜,胡萝卜和亚军豆的总和来获得前三名

任何帮助将不胜感激

veggies_2015.dat格式:

1 
Marlon Holmes 
18.86 
13.02 
13.36

这样的50条记录

1 个答案:

答案 0 :(得分:1)

您需要一个不同的键功能进行排序:

def by_veg_sum(record):
    return sum(record[entry] for entry in ['Cucumber','Carrot','Runner Bean'])

并在您的代码中使用它:

sorted_data = sorted(data, key=by_veg_sum, reverse=True)

您可以添加调试打印以查看计算的总和:

def by_veg_sum(record):
    s = sum(record[entry] for entry in ['Cucumber','Carrot','Runner Bean'])
    print s
    return s

如果要将实际总和添加到记录中,可以执行以下操作:

for record in data:
    record['sum'] = sum(record[entry] for entry in
                        ['Cucumber','Carrot','Runner Bean'])
sorted_data = sorted(data, key=itemgetter('sum'), reverse=True)

打印每条记录的选定值,就像从普通字典中打印一样:

for entry in sorted_data[:10]:
    for key in ['Competitor Number', 'Competitor Name', 'sum']:
        print entry[key]
    print