在 Python 中对非整数求和

时间:2023-01-01
本文介绍了在 Python 中对非整数求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 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]

这篇关于在 Python 中对非整数求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:在列表中添加项目,直到它们的总和超过阈值 下一篇:索引对之间子数组中值的 Numpy 总和

相关文章

最新文章