[英]Python. ValueError could not convert string to float:
I'm trying to produce the average of numbers in a specified column in a text file. 我正在尝试生成文本文件中指定列中数字的平均值。 I am receiving an error that python could not convert string to float, although I don't see where I could be passing it an invalid string. 我收到错误消息,python无法将字符串转换为浮点数,尽管我看不到可以将无效字符串传递给哪里。
def avg_col(f, col, delim=None, nhr=0):
"""
file, int, str, int -> float
Produces average of data stored in column col of file f
Requires: file has nhr header rows of data; data is separated by delim
>>> test_file = StringIO('0.0, 3.5, 2.0, 5.8, 2.1')
>>> avg_col(test_file, 2, ',', 0)
2.0
>>> test_file = StringIO('0.0, 3.5, 2.0, 5.8, 2.1')
>>> avg_col(test_file, 3, ',', 0)
5.8
"""
total = 0
count = 0
skip_rows(f, nhr)
for line in f:
if line.strip() != '':
data = line.split(delim)
col_data = data[col]
total = sum_data(col_data) + total
count = len(col_data) + count
return total / count
def sum_data(lod):
'''
(listof str) -> Real
Consume a list of string-data in a file and produce the sum
>>> sum_data(['0'])
0.0
>>> sum_data(['1.5'])
1.5
'''
data_sum = 0
for number in lod:
data_sum = data_sum + float(number)
return data_sum
You are passing in one string to sum_lod()
: 您正在将一个字符串传递给sum_lod()
:
data = line.split(delim)
col_data = data[col]
total = sum_data(col_data) + total
data
is a list of strings, data[col]
is then one element. data
是一个字符串列表,然后data[col]
是一个元素。
sum_data()
on the other hand expects an iterable : sum_data()
期望可迭代 :
def sum_data(lod):
# ...
for number in lod:
Iterating over a number then gives you the individual characters: 遍历一个数字,然后为您提供各个字符:
>>> for element in '5.8':
... print element
...
5
.
8
Trying to turn each element of such a string can easily lead to you trying to convert characters that are not numbers to a float: 尝试将这样一个字符串的每个元素都转起来很容易导致您尝试将非数字字符转换为浮点数:
>>> float('.')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: .
Either pass in a list of strings: 要么传递一个字符串列表 :
total += sum_data([col_data])
count += 1
or simply use float()
on the one element you have: 或仅在您拥有的一个元素上使用float()
:
total += float(col_data)
count += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.