0

为什么 sum 不能自动取正确的零值?

>>> sum((['1'], ['2']))

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    sum((['1'], ['2']))
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> sum((['1'], ['2']), [])
['1', '2']

像这样实现很简单:

>>> def sum(s, start=None):
    it = iter(s)
    n = next(it)
    if start is None:
        start = type(n)()
    return n + __builtins__.sum(it, start)

>>> sum((['1'], ['2']))
['1', '2']
>>>

但是 sum 无论如何都不会加入字符串,所以也许它只是为了鼓励对不同的“求和”使用正确的方法。

另一方面,如果它仅用于数字,为什么sum_numberssum作为名称来说明。

编辑:要处理空序列,我们必须添加一些代码:

>> sum([])

Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    sum([])
  File "<pyshell#28>", line 3, in sum
    n = next(it)
StopIteration
>>> def sum(s, start=None):
    it = iter(s)
    try:
        n= next(it)
    except:
        return 0

    if start is None:
        start = type(n)()
    return n + __builtins__.sum(it, start)

>>> sum([])
0
>>> 
4

1 回答 1

2

在一般情况下,不可能推断出零值。如果可迭代对象生成没有零参数构造函数的用户定义类的实例怎么办?正如您所展示的,您自己提供它很容易。

于 2012-06-12T19:00:36.037 回答