[英]Can I get sum of a list values (not occurrences of index values) in Python
I have an output list like, 我有一个输出列表,
[['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]
So I want to get sum of the each same values. 所以我想获得每个相同值的总和。 According to this list the output should be,
根据此清单,输出应为
happy weight : 3.5
0 count : 4
sad weight : 1
I tried to find a way to do this and I still fail to find a correct way for that. 我试图找到一种方法来执行此操作,但仍然找不到正确的方法。 Can anyone tell me can I get the output as I expected.
谁能告诉我我能得到预期的输出吗?
The more static way of doing it. 更静态的方法。
l=[['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'],
['happy', 1]]
print(sum(1 for x in l if x[0]=='0'))
print(sum(x[1] for x in l if x[0]=='happy'))
print(sum(x[1] for x in l if x[0]=='sad'))
This implementation fits your criteria, but as @ScottHunter said, there is some vagueness. 此实现符合您的条件,但是正如@ScottHunter所说,存在一些模糊性。
lst = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]
def update_count(item_key, increase, dictionary):
try:
dictionary[item_key] += increase
except KeyError:
dictionary[item_key] = increase
item_counts = dict()
for item in lst:
size = len(item)
if size == 1:
update_count(item[0], 1, item_counts)
elif size == 2:
update_count(item[0], item[1], item_counts)
else:
print("Too many elements in item!")
print(item_counts)
Or you can use collections.Counter
if you prefer to leave out the try/except
: 或者,您可以使用
collections.Counter
如果您希望省略try/except
:
from collections import Counter
lst = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]
item_counts = Counter()
for item in lst:
size = len(item)
if size == 1:
item_counts[item[0]] += 1
elif size == 2:
item_counts[item[0]] += item[1]
else:
print("Too many elements in item!")
print(item_counts)
Using defaultdict
from collections
: 从
collections
使用defaultdict
:
from collections import defaultdict
lst = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]
item_counts = defaultdict(int) # the int() func returns 0 if key doesn't exist
for item in lst:
size = len(item)
if size == 1:
item_counts[item[0]] += 1
elif size == 2:
item_counts[item[0]] += item[1]
else:
print("Too many elements in item!")
print(item_counts)
x = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]
d = {k: 0 for k in set([i[0] for i in x])}
for i in x:
if len(i) == 1:
d[i[0]] += 1
elif len(i) == 2:
d[i[0]] += i[1]
for k, v in d.items():
print(k, v)
using a dict 使用字典
If you don't mind using an 3rd party extension, you could use iteration_utilities.groupedby
1 : 如果您不介意使用第3方扩展名,则可以使用
iteration_utilities.groupedby
1 :
lst = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]
from iteration_utilities import groupedby
for key, value in groupedby(lst, lambda x: x[0]).items():
if key == '0':
print(key, 'count:', len(value))
else:
print(key, 'weight:', sum(x[1] for x in value))
which prints: 打印:
0 count: 4
happy weight: 3.5
sad weight: 1
1 Disclaimer: I'm the author of that library 1免责声明:我是该图书馆的作者
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.