在字符串为元组的列表中对相同项的值求和 [英] To sum up values of same items in a list of tuples while they are string

查看:65
本文介绍了在字符串为元组的列表中对相同项的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的元组列表:

If I have list of tuples like this:

my_list = [('books', '$5'), ('books', '$10'), ('ink', '$20'), ('paper', '$15'), ('paper', '$20'), ('paper', '$15')] 

我如何将列表转到此:

[('books', '$15'), ('ink', '$20'), ('paper', '$50')]

即当两个项目都是元组中的字符串时,添加相同项目的费用.我有价格项目是字符串的问题.任何提示将不胜感激.非常感谢!

i.e. to add the expense of same item while both the items are string in the tuples. I have problem with the price items being string. Any hint would be greatly appreciated. Thanks a lot!

我以这种方式获得第一张清单:

I am getting the first list in this way:

my_list=[]
for line in data:
        item, price  = line.strip('\n').split(',') 
        cost = ["{:s}".format(item.strip()), "${:.2f}".format(float(price))]
        my_list.append(tuple(cost))

现在my_list应该看起来像上面给出的那样.

Now my_list should look like given above.

推荐答案

您可以使用

You can use defaultdict to do this:

>>> from collections import defaultdict
>>> my_list = [('books', '$5'), ('books', '$10'), ('ink', '$20'), ('paper', '$15'), ('paper', '$20'), ('paper', '$15')] 
>>> res = defaultdict(list)
>>> for item, price in my_list:
...     res[item].append(int(price.strip('$')))
... 
>>> total = [(k, "${}".format(sum(v))) for k, v in res.items()]
>>> total
[('ink', '$20'), ('books', '$15'), ('paper', '$50')]

这篇关于在字符串为元组的列表中对相同项的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆