希望使用sum函数获得值的和,但一直得到TypeError:不支持的操作数类型+:'int'和'list'
ones = {'alpha': [2662.0,80], 'beta': [3646.7,50], 'gamma': [250.8,100]}
twos = {}
for k,(v,q) in ones.items():
if k not in twos:
twos[k] = []
twos[k].append(v)
print(twos)
sum_twos = sum(twos.values())
print(sum_twos)
有点奇怪,但一个解决方案可以是:
ones = {
'alpha': [2662.0,80],
'beta': [3646.7,50],
'gamma': [250.8,100]
}
twos = {}
for k,(v,q) in ones.items():
if k not in twos:
twos[k] = []
twos[k].append(v)
sum_twos = sum([sum(v) for v in twos.values()])
print(sum_twos)
输出:
6559.5
我找到了另一种方法:不将值存储在列表中,而是将它们存储在float中。
ones = {'alpha': [2662.0,80], 'beta': [3646.7,50], 'gamma': [250.8,100]}
twos = {}
for k,(v,q) in ones.items():
if k not in twos:
twos[k] = float()
twos[k] += v
print('twos','=', twos)
sum_twos = sum(twos.values())
print('sum_twos',':', sum_twos)
输出:2 ={"α":2662.0,"beta":3646.7,"伽马":250.8}
sum_two: 6559.5