我试图在放入列表后将csv文件中的值相加,我想将它们全部加在一起。列表:
'50', '51', '53', '55', '56', '56', '56', '61', '64', '67', '68', '71', '79', '81', '86', '86', '87', '94', '96', '98', '99' 'Score'
代码从csv获取这些值并将vales放入列表
import csv
f=open('IT_Programming_data.csv')
csv_f = csv.reader(f)
score = []
for row in csv_f:"score"
score.append(row[1])
a = score
b = sum(a)
print (b)
f.close()
当我尝试总结列表时,我收到错误:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
当你这样做时总和有效:
a = [1,3,4]
b = sum(a)
print (b)
返回' 8'
如何使用从csv导入的列表,我不知道
答案 0 :(得分:0)
您尝试添加一个字符串和一个会引发ValueError的数字,请尝试使用此代码来处理异常:
import csv
f = open('IT_Programming_data.csv')
csv_f = csv.reader(f)
score = []
for row in csv_f:
try:
num = int(row[1].strip()) # try to switch type
score.append(num)
except Exception,error: # fail to switch, print error
print(error)
b = sum(score)
print(b)
f.close()
答案 1 :(得分:0)
问题是,您的列表条目格式不正确。您可以通过打印循环中的内容来捕获此错误:
import csv
f=open('testlist.csv')
csv_f = csv.reader(f)
score = []
for row in csv_f:
print(row)
score.append(int(row[1].strip().strip("'")))
a = score
b = sum(a)
print (b)
f.close()
输出类似于["'50'", " '51'", " '53'", " '55'", " '56'", " '56'", " '56'",..., " '99' 'Score'"]
所以你可以在这里看到你的条目有时以空格开头,它们包括额外的" ' &#34 ;.你必须通过删除最后一个条目来清理你的列表,然后你必须摆脱空白,然后你必须摆脱额外的" ' &#34 ;.然后你必须把这个全部转换成int。这是在上面的循环中完成的
答案 2 :(得分:0)
尽量不要在循环中使用try-except。它会严重损害性能并且看起来非常不专业,尤其是当内置isdigit()
时。
import csv
f = open('IT_Programming_data.csv')
csv_f = csv.reader(f)
score = []
for row in csv_f:
if row[1].isdigit():
num = int(row[1]) # try to switch type
score.append(num)
b = sum(score)
print(b)
f.close()
答案 3 :(得分:0)
试试这个:
b= [sum(int(x)) for x in a]