我有列表:
['apples', 400, 'sweets', 300, 'apples', 750]
应用函数后:
def Convert(a):
it = iter(a)
res_dct = dict(zip(it, it))
return res_dct
我得到结果:{'apples': 750, 'sweets': 300}
但我需要:{'apples': 1150, 'sweets': 300}
或者,您也可以尝试使用集合defaultdict和Counter实现相同的结果。这只是为了遵循您的原始代码和流程:
from collections import Counter, defaultdict
# data = ['apples', 400, 'sweets', 300, 'apples', 750]
def convert(A):
result = defaultdict(Counter)
it = iter(A)
for fruit, count in zip(it, it):
if fruit not in result:
result[fruit] = count
else:
result[fruit] += count
return result
运行:
print(convert(data))
# defaultdict(<class 'collections.Counter'>, {'apples': 1150, 'sweets': 300})