Python sum()函数

2023-05-16

Python里的sum函数

    • 语法
    • 例子
      • 1. 列表中的元素为数字:
      • 2. 列表中的元素为字符串:
      • 3. 列表中元素为列表

语法

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'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python sum()函数 的相关文章

随机推荐