[英]Python: ValueError: invalid literal for int() with base 10: '"'
I'm creating code to get the average score in a CSV file. 我正在创建代码以获取CSV文件中的平均分数。
CSV file looks like this: CSV文件如下所示:
5 Ser15
4 Ser15
3 Ser15
1st column are the scores, the second are the usernames. 第一列是分数,第二列是用户名。
This is my code so far: 到目前为止,这是我的代码:
def av():
with open("SciMedreport.csv","r") as f:
average = 0
Sum = 0
row_count = 0
for row in f:
column = row.split(',')
i=(int(column[0]))
Sum += i
row_count += 1
average = Sum / row_count
return 'The average is:', average
av()
But this error appears... 但是出现此错误...
i=int(column[0])
ValueError: invalid literal for int() with base 10: '"'
When I print the whole row to check, this appears: 当我打印整行进行检查时,将显示:
def av():
with open("SciMedreport.csv","r") as f:
average = 0
Sum = 0
row_count = 0
for row in f:
print(row)
av()
This is the result: 结果如下:
5,Ser15
""
5,Ser15
""
4,Ser15
Anyone know of a way to fix this, or an alternative way to work out the average?? 任何人都知道解决此问题的方法,或计算平均值的另一种方法?
当您尝试用','分割行时,因为没有,整个字符串将被返回并且尝试将其转换为int()给您错误,请尝试使用''
I am able to see a couple of errors in the code. 我可以在代码中看到几个错误。
for row in f:
(1) for column in row.split(','):
(2) i=(int(column))
Sum += i
row_count += 1
(3) average = Sum / len(column)
(1) When you split the row, what you get back is basically an array/list. (1)拆分行时,您得到的基本上是一个数组/列表。 In your case, it would be ['5', 'Ser15]
. 在您的情况下,它将为['5', 'Ser15]
。 And instead of a for loop, you might want to change the code as follows: 而不是for循环,您可能想要更改代码,如下所示:
for row in f:
columns_list = row.split(',')
i=(int(columns_list[0]))
Sum += i
row_count += 1
average = Sum / row_count
(2) Now you can't convert a list to an integer. (2)现在您无法将列表转换为整数。 What you might be interested in is i = int(column[0])
ie first number in the list ie first column of your CSV file. 您可能感兴趣的是i = int(column[0])
即列表中的第一个数字,即CSV文件的第一列。
(3) You want to find the average of all rows, right? (3)您想找到所有行的平均值,对吗? Souldn't it be average = Sum / row_count
? 它不是average = Sum / row_count
吗?
def av():
with open("SciMedreport.csv","r") as f:
average = 0
Sum = 0
row_count = 0
divisor = 0
for row in f:
row_count += 1
if row_count%2 == 0: # if it doesn't work, try changing to 1
# print(row.split(','))
divisor += 1
# write rest of the code here, Sum += i etc.
columns_list = row.split(',')
i = int(columns_list[0])
Sum += i
average = Sum / divisor
def av():
with open("SciMedreport.csv","r") as f:
average = 0
Sum = 0
row_count = 0
divisor = 0
for row in f:
row_count += 1
if row_count%2 == 0: # if it doesn't work, try changing to 1
# print(row.split(','))
divisor += 1
# write rest of the code here, Sum += i etc.
columns_list = row.split(',')
i = int(columns_list[0])
Sum += i
average = Sum / divisor
Thank you to user3903448! 谢谢user3903448!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.