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

时间:2015-04-02 16:18:26

标签: python sum

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()函数只是一种更加pythonic的方式reduce(lambda i, sum:i+sum)。并且reduce允许我合并字符串,而sum()没有。

From python documentation for sum()

  

iterable的项目通常是数字,而起始值则不是   允许是一个字符串。

为什么?

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

1 个答案:

答案 0 :(得分:5)

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

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

您改为使用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__操作的任何其他类型,但您必须指定合理的起始值。你可以总结一下&#39;列表,例如:

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

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