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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值