在 Python 中对非整数求和

2022-01-09 00:00:00 python sum

问题描述

是否可以在 Python 中取非整数的总和?

Is it possible to take the sum of non-integers in Python?

我试过命令

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

获取[1, 2],但报错

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

我怀疑 sum 试图将 0 添加到列表 [1] 中,导致失败.我确信有很多技巧可以解决这个限制(将东西包装在一个类中,并手动实现 __radd__),但是有没有更优雅的方法来做到这一点?

I suspect sum tries to add 0 to the list [1], resulting in failure. I'm sure there are many hacks to work around this limitation (wrapping stuff in a class, and implementing __radd__ manually), but is there a more elegant way to do this?


解决方案

看起来你想要这个:

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

你是对的,它试图将 0 添加到 [1] 并得到一个错误.解决方案是给 sum 一个额外的参数来给出起始值,对你来说这将是一个空列表.

You're right that it's trying to add 0 to [1] and getting an error. The solution is to give sum an extra parameter giving the start value, which for you would be the empty list.

正如 gnibbler 所说,sum 并不是连接事物的好方法.如果你只是想聚合一个序列,你可能应该使用 reduce 而不是为了使用 sum 而创建自己的 __radd__ 函数.这是一个示例(与 sum 具有相同的不良行为):

As gnibbler says, though, sum is not a good way to concatenate things. And if you just want to aggregate a sequence of things, you should probably use reduce rather than make your own __radd__ function just to use sum. Here's an example (with the same poor behavior as sum):

>>> reduce(lambda x, y: x+y, [[1],[2]])
[1, 2]

相关文章