Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试对';STR型中的s_Python - Fatal编程技术网

Python 尝试对';STR型中的s

Python 尝试对';STR型中的s,python,Python,我一直在尝试使用ibm_db模块对从DB2表的查询中获得的list['6134,15','20432,65','10588795,61']的内容求和(我还使用pandas来框显结果)。这些是美元金额,但它们是作为字符串检索的,因此我无法对它们求和。我试过: # This gets me the list from the column I'm interested in. amtTot = maind.get('INVOICE_TOTAL') for char in amtTot:

我一直在尝试使用ibm_db模块对从DB2表的查询中获得的list['6134,15','20432,65','10588795,61']的内容求和(我还使用pandas来框显结果)。这些是美元金额,但它们是作为字符串检索的,因此我无法对它们求和。我试过:

# This gets me the list from the column I'm interested in.
amtTot = maind.get('INVOICE_TOTAL') 

for char in amtTot:
    a = char.replace(",",".") 
    b = float(a) 
    print(b)

作为回报,我得到每一个值——这没关系,但我需要它们的总和。我试图应用类似于
sum(b)
的东西,但我得到了错误“float是不可计算的”。如果我尝试使用
int
而不是
float
,我会得到“以10为基数的int()无效文本:'6134,15'。

最简单的解决方案是使用一个变量来跟踪和:

total = 0
for char in amtTot:
    a = char.replace(",",".") 
    b = float(a) 
    print(b)
    total += b

print(total)
试试这个:

cleanList = [float(i.replace(",", ".")) for i in amtTot]
sum(cleanList)

希望这有帮助

如果您需要一个行程序,
total=sum([float(char.replace(“,”,“,”))for char in amTot])
应该完成这项工作。不客气。此外,错误意味着函数
sum
需要一个迭代器作为参数
sum
获取一个类似列表、集合或numpy数组等的迭代器,并返回其中项目的总和。这完全解决了我的问题。我真的很感谢你的帮助!