gpt4 book ai didi

python - 如何对我从 python 数据库中获得的列表求和。错误类型错误 : unsupported operand type(s) for : 'int' and 'tuple'

转载 作者:太空宇宙 更新时间:2023-11-04 10:49:23 25 4
gpt4 key购买 nike

如何在 python 中对从数据库中获取的列表中的元素求和。每次我尝试时都会收到错误 TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

def sum_num(mylist):
return sum(mylist)

当我打印我的列表时,我得到这个 [(52642,), (57127,), (9000,), (29000,), (350000,), (21000,), (41400,), (21600, )] 是我表中的数据

mylist 是从我的数据库中的数据填充的列表。谁能告诉我哪里有错误?还有其他方法吗?

当我做 print sum(mylist[1]+ mylist[2]) 时,我得到了正确的答案

最佳答案

lst = [ i[0] for i in mylist]
sum(lst)

这种方式需要创建另一个列表,但这是您也可以考虑的替代方法。

编辑:

像已经提到的其他人一样,mylist 的元素是元组。由于 mylist 中的每个元素在其第一个位置都有一个数值 (int),因此您可以对列表中每个元素(元组)位于位置 0 的值求和.

关于python - 如何对我从 python 数据库中获得的列表求和。错误类型错误 : unsupported operand type(s) for : 'int' and 'tuple' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14915600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com