我有一個包含名稱和數字的串列。對于串列中具有相同名稱的所有專案,我想計算這些數字的總和。
請注意,我不能使用 numpy 函式。
這是我的二維串列:
list = [('apple', 3), ('apple', 4), ('apple', 6), ('orange', 2), ('orange', 4), ('banana', 5)]
然后將具有相同名稱的數字相加,預期輸出如下。
預期輸出:
apple: 13
orange: 6
banana: 5
uj5u.com熱心網友回復:
使用一個簡單的回圈和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)
輸出:{'apple': 13, 'orange': 6, 'banana': 5}
對于格式化輸出:
for key, val in d.items():
print(f'{key}: {val}')
輸出:
apple: 13
orange: 6
banana: 5
uj5u.com熱心網友回復:
一種方法是使用默認字典:
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 中的關鍵字,因此覆寫它們是“不良”行為。
uj5u.com熱心網友回復:
您可以迭代此串列,并使用 adict來計算所有水果:
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}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533909.html
上一篇:保留串列的唯一元素
下一篇:C 中的一行用戶輸入賦值
