为什么 Python builin sum() 函数不支持字符串?

Why Python builin sum() function does not support strings?

sum() 函数仅适用于数字,不适用于字符串。

  int_lst = [1, 2]
  sum(int_lst)
=> 3

   str_lst = ['a', 'b']
   sum(str_lst)
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

我发现这种行为很奇怪,因为 sum() 函数只是执行 reduce(lambda i, sum:i+sum) 的一种更 pythonic 的方式。并 reduce 允许我连接字符串,sum() 不行。

From python documentation for sum()

The iterable‘s items are normally numbers, and the start value is not allowed to be a string.

为什么?

OOP 教会我们制作多态的东西,因为它很灵活。

求和字符串效率非常低;在循环中对字符串求和需要为每两个连接的字符串创建一个新字符串,只有在下一个字符串与该结果连接时才会再次销毁。

例如,为了求和 ['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'],您将创建 'foobar',然后是 'foobarbaz',然后是 'foobarbazspam',然后是 'foobarbazspamham',最后是 'foobarbazspamhameggs',丢弃除最后一个字符串对象之外的所有对象。

您将改用 str.join() 方法:

''.join(str_list)

创建一个新字符串并复制组成字符串的内容。

请注意 sum() 使用默认起始值​​ 0,这就是您收到特定异常消息的原因:

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

您可以给 sum() 一个不同的起始值作为第二个参数;对于会给您更有意义的错误消息的字符串:

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

该功能不仅限于数字;您可以将它用于定义 __add__ 操作的任何其他类型,但您必须指定一个合理的起始值。您可以 'sum' 列表,例如:

>>> sum([['foo', 'bar'], ['ham', 'spam']], [])
['foo', 'bar', 'ham', 'spam']

但请注意第二个 (start) 参数的 [] 值!这也和求和字符串一样低效;有效的方法是使用 list(itertools.chain.from_iterable(list_of_lists)).