Python sum()函数

语法

sum(iterable, start)

  • 参数1 iterable,一个可迭代对象,可以是列表、字典、元祖等,重要的是可迭代对象中的元素是可相加的。比如数字、列表是可加的,字符串就不是可加的
  • 参数2 start,可选参数,他会被加到可迭代对象的和中,默认是0

例子

1. 列表中的元素为数字:

>>> sum([1,2,3,4])     # print 10
>>> sum([1,2,3,4],10)  # print 20

2. 列表中的元素为字符串:

sum(['apple','banana'])    # 报错,不能把整数和字符串相加

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

start参数给成字符串:

sum(['apple','banana'], 'peach')   # 报错,sum()不能拼接两个字符串

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]

3. 列表中元素为列表

>>> sum([['a','b','c','d'], ['e','f','g']], [])  # print ['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> sum([['a','b','c','d'], ['e','f','g']])  # 报错,相当于把列表和数字0相加

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
  • 19
    点赞
  • 101
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: Pythonsum函数用于计算可迭代对象中元素的总和。它接受两个参数,第一个参数是可迭代对象,可以是列表、字典、元组等,重要的是可迭代对象中的元素是可相加的。第二个参数是可选参数,它会被加到可迭代对象的和中,默认是0。\[1\]\[3\] 例如,如果可迭代对象是一个列表,其中的元素是数字,那么sum函数将返回这些数字的总和。例如,sum(\[1, 2, 3, 4\])将返回10。如果指定了第二个参数,它将被加到总和中。例如,sum(\[1, 2, 3, 4\], 10)将返回20。\[3\] 然而,需要注意的是,如果可迭代对象中的元素不可相加,那么sum函数将会报错。例如,如果可迭代对象是一个列表,其中的元素是字符串,那么sum函数将会报错,因为整数和字符串不能相加。\[2\]\[3\] 总之,Pythonsum函数用于计算可迭代对象中元素的总和,但要确保可迭代对象中的元素是可相加的。 #### 引用[.reference_title] - *1* [(Pythonsum函数的用法](https://blog.csdn.net/qq_44771627/article/details/122548684)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Python sum()函数](https://blog.csdn.net/Robert_Q/article/details/123032880)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值