-1
我试图在文本文件中的指定列中生成数字的平均值。我收到一个错误,蟒蛇无法将字符串转换为浮点数,尽管我没有看到我可以传递一个无效字符串的位置。Python。 ValueError无法将字符串转换为浮点型:
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
你需要共享的完整追踪,如果你可以提供一些重现异常的示例数据,这比仅发布的代码更有帮助。 – 2015-01-26 20:24:10