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

2022-11-05Python开发问题
3

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

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11