Python中的sum求和、reduce求和以及字典相加

Python中的sum求和、reduce求和以及字典相加

Sum求和

sum()函数语法: sum(iterable[, start])

其中, iterable – 可迭代对象,如:列表(list)、元组(tuple)、集合(set)、字典(dictionary)…

start – 指定相加的参数,如果没有设置这个值,默认为0…

即sum()最后求得的值 = 可迭代对象里面的数加起来的总和(字典:key值相加) + start的值(如果没写start的值,则默认为0)

a. 列表求和:

print(sum([2, 3]))

b. 元组求和:

print(sum((1, 2)))

c. 字典求和:

print(sum({1:'xiaoming', 2:'xiaozhang'}))

结果为: 3

d. range求和:

print(sum(range(1, 4), 2))

字典key相加,不同key保留

方法1:

def merge_dict(x, y):

for i, j in x.items():

if i in y.keys():

y[i] += j

else:

y[i] = j

return y

x = {'a': 1, 'b': 3, 'c': 7}

y = {'b': 2, 'd': 4}

print(merge_dict(x, y))

结果为:

{‘b’: 5, ‘d’: 4, ‘a’: 1, ‘c’: 7}

方法2:

x = {'a':1, 'b':2, 'c':3}

y = {'c': 4, 'd': 5}

from collections import Counter

X, Y = Counter(x), Counter(y)

z = dict(X+Y)

print(z)

结果为:

{‘a’: 1, ‘b’: 2, ‘c’: 7, ‘d’: 5}

reduce求和

https://blog.csdn.net/weixin_43283397/article/details/95632329

相关推荐