在 Python 中求和非整数 [英] Summing non-integers in Python
问题描述
是否可以在 Python 中取非整数的总和?
我尝试了命令
sum([[1], [2]])
得到[1, 2]
,但它给出了错误
回溯(最近一次调用):文件<pyshell#28>",第 1 行,在 <module> 中.总和([[1], [2]])类型错误:+ 不支持的操作数类型:'int' 和 'list'
我怀疑 sum 试图将 0 添加到列表 [1]
,导致失败.我确信有很多技巧可以解决这个限制(将东西包装在一个类中,并手动实现 __radd__
),但是有没有更优雅的方法来做到这一点?
看起来你想要这个:
<预><代码>>>>sum([[1],[2]], [])[1, 2]您是对的,它试图将 0 添加到 [1] 并出现错误.解决方案是给 sum
一个额外的参数,给出起始值,对你来说就是空列表.
不过,正如 gnibbler 所说,sum
不是连接事物的好方法.如果你只想聚合一系列的东西,你可能应该使用 reduce
而不是为了使用 sum
而创建你自己的 __radd__
函数.这是一个示例(与 sum
具有相同的不良行为):
Is it possible to take the sum of non-integers in Python?
I tried the command
sum([[1], [2]])
to get [1, 2]
, but it gives the error
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
sum([[1], [2]])
TypeError: unsupported operand type(s) for +: 'int' and 'list'
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?
It looks like you want this:
>>> sum([[1],[2]], [])
[1, 2]
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.
Edit: 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]
这篇关于在 Python 中求和非整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!