带有列表参数的 Python sum() 函数

Python sum() function with list parameter(带有列表参数的 Python sum() 函数)
本文介绍了带有列表参数的 Python sum() 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要使用 sum() 函数来对列表中的值求和.请注意,这与使用 for 循环手动添加数字不同.我以为它会像下面这样简单,但我收到 TypeError: 'int' object is not callable.

I am required to use the sum() function in order to sum the values in a list. Please note that this is DISTINCT from using a for loop to add the numbers manually. I thought it would be something simple like the following, but I receive TypeError: 'int' object is not callable.

numbers = [1, 2, 3]
numsum = (sum(numbers))
print(numsum)

我查看了一些其他解决方案,这些解决方案涉及设置 start 参数、定义地图或在 sum() 中包含 for 语法,但我没有这些变化的任何运气,并且无法弄清楚发生了什么.有人可以为我提供最简单的 sum() 示例,该示例将汇总一个列表,并解释为什么它会以这种方式完成?

I looked at a few other solutions that involved setting the start parameter, defining a map, or including for syntax within sum(), but I haven't had any luck with these variations, and can't figure out what's going on. Could someone provide me with the simplest possible example of sum() that will sum a list, and provide an explanation for why it is done the way it is?

推荐答案

你在其他地方使用过变量 sum 吗?这样就可以解释了.

Have you used the variable sum anywhere else? That would explain it.

>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

sum 这个名字现在不再指向函数,它指向一个整数.

The name sum doesn't point to the function anymore now, it points to an integer.

解决方案:不要将变量称为 sum,将其称为 total 或类似的名称.

Solution: Don't call your variable sum, call it total or something similar.

这篇关于带有列表参数的 Python sum() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

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 求和?)