Python. ValueError could not convert string to float:(蟒蛇。ValueError无法将字符串转换为浮点型:)
本文介绍了蟒蛇。ValueError无法将字符串转换为浮点型:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试生成文本文件中指定列中数字的平均值。我收到了一个错误,即虽然我不知道我可以在哪里向它传递无效的字符串,但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
推荐答案
您正在将一个字符串传递给sum_lod():
data = line.split(delim)
col_data = data[col]
total = sum_data(col_data) + total
data是字符串列表,data[col]是一个元素。
sum_data()另一方面,需要可迭代:
def sum_data(lod):
# ...
for number in lod:
迭代一个数字,然后得到各个字符:
>>> for element in '5.8':
... print element
...
5
.
8
尝试转换此类字符串的每个元素很容易导致您尝试将非数字的字符转换为浮点型:
>>> float('.')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: .
传入字符串列表:
total += sum_data([col_data])
count += 1
或只在您拥有的一个元素上使用float():
total += float(col_data)
count += 1
这篇关于蟒蛇。ValueError无法将字符串转换为浮点型:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:蟒蛇。ValueError无法将字符串转换为浮点型:
基础教程推荐
猜你喜欢
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
