我正在尝试将字符串列表转换为浮动列表。我尝试过列表理解、映射,并简单地将其写在for循环中。我真的不想使用映射,因为即使使用list(map)
,我似乎也无法将其恢复到正确的列表中。
到目前为止,我的所有尝试都没有成功,因为我在为Python 3x找到正确的语法时遇到了困难。我最近的尝试似乎显示出了希望,但我仍然得到以下错误。
Traceback (most recent call last):
File "G:/test.py", line 56, in <module>
heartdis_flt.append(float(item))
TypeError: float() argument must be a string or a number, not 'list'
这是我正在使用的代码:
heartdis = heartdis[5:]
heartdis_flt = []
for item in heartdis:
heartdis_flt.append(float(item))
print(heartdis_flt)
heartdis
是从CSV文件创建的字符串列表。
有人能解释一下正确的语法或者我的逻辑中的一些缺陷吗?
就像@utdemir评论的那样,代码的问题在于将列表视为字符串。你确实可以使用
itertools.chain
,但也许你想首先改变阅读heartdis
的方式。我不知道您是如何读取CSV文件的,但是如果您使用的是csv
模块,我认为您不应该将列表列表作为输出。不管怎样,你应该听听我的意见。我找到了有用的东西。我使用itertools将列表列表更改为一个列表,然后将其全部转换为float。
相关问题 更多 >
编程相关推荐