[英]I have a 3d list of strings and numbers. I need to calculate the sum of each string and then percent in python
[英]I have a 2d list of strings and numbers. I want to get the sum of all numbers that have the same string. Code is in python
我有一个包含名称和数字的列表。 对于列表中具有相同名称的所有项目,我想计算这些数字的总和。
请注意,我无法使用 numpy function。
这是我的二维列表:
list = [('apple', 3), ('apple', 4), ('apple', 6), ('orange', 2), ('orange', 4), ('banana', 5)]
然后将具有相同名称的数字相加,预期的 output 如下。
预计 output:
apple: 13
orange: 6
banana: 5
一种方法是使用默认字典:
from collections import defaultdict
d = defaultdict(list) # all elements in the dictionary will be a list by default
l = [('apple', 3), ('apple', 4), ('apple', 6), ('orange', 2), ('orange', 4), ('banana', 5)]
for name, number in l:
d[name].append(number)
for key, value in d.items():
print(f"{key}: {sum(value)}")
或者直接:
from collections import defaultdict
d = defaultdict(float) #
l = [('apple', 3), ('apple', 4), ('apple', 6), ('orange', 2), ('orange', 4), ('banana', 5)]
for name, number in l:
d[name] += number
print(d)
顺便说一句, list
是 python 中的关键字,因此覆盖它们是“不良”行为。
您可以迭代此列表,并使用dict
来计算所有水果:
list = [('apple', 3), ('apple', 4), ('apple', 6), ('orange', 2), ('orange', 4), ('banana', 5)]
final_dict = {}
for fruit, count in list:
if fruit not in final_dict:
final_dict[fruit] = count
else:
final_dict[fruit] += count
print(final_dict)
输出:
{'apple': 13, 'orange': 6, 'banana': 5}
使用一个简单的循环和dict.get
:
l = [('apple', 3), ('apple', 4), ('apple', 6),
('orange', 2), ('orange', 4), ('banana', 5)]
d = {}
for key, val in l:
d[key] = d.get(key, 0) + val
print(d)
Output: {'apple': 13, 'orange': 6, 'banana': 5}
对于格式化的 output:
for key, val in d.items():
print(f'{key}: {val}')
Output:
apple: 13
orange: 6
banana: 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.