在 Python 中对非整数求和

Summing non-integers in Python(在 Python 中对非整数求和)
本文介绍了在 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 中对非整数求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)