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

时间:2023-01-01
本文介绍了带有列表参数的 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() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:python - 如何并行化python numpy中的总和计算? 下一篇:N个列表元素的总和python

相关文章

最新文章