我有一个输出列表,如
[['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]
所以我想得到每个相同值的总和。根据这个列表,输出应该是,
happy weight : 3.5
0 count : 4
sad weight : 1
我试图找到一种方法来做到这一点,但我仍未找到正确的方法。任何人都可以告诉我,我可以按预期得到输出。
答案 0 :(得分:4)
更静态的做法。
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'))
答案 1 :(得分:2)
此实施符合您的标准,但正如@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)
如果您想省略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)
使用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)
答案 2 :(得分:1)
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)
使用词典
答案 3 :(得分:1)
您可以使用Counter
:
l = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]
from collections import Counter
c = Counter()
for v in l:
c[v[0]] += 1 if len(v) == 1 else v[1]
print c # Counter({'0': 4, 'happy': 3.5, 'sad': 1})
答案 4 :(得分:1)
如果您不介意使用第三方扩展程序,可以使用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))
打印:
0 count: 4
happy weight: 3.5
sad weight: 1
1 免责声明:我是该图书馆的作者