"TypeError: 浮点数参数必须是字符串或数字,不能是列表。将字符串列表转换为浮点数列表"

2024-06-16 10:42:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将字符串列表转换为浮动列表。我尝试过列表理解、映射,并简单地将其写在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文件创建的字符串列表。

有人能解释一下正确的语法或者我的逻辑中的一些缺陷吗?


Tags: 字符串inmapmost列表for错误语法
2条回答

就像@utdemir评论的那样,代码的问题在于将列表视为字符串。你确实可以使用itertools.chain,但也许你想首先改变阅读heartdis的方式。我不知道您是如何读取CSV文件的,但是如果您使用的是csv模块,我认为您不应该将列表列表作为输出。不管怎样,你应该听听我的意见。

我找到了有用的东西。我使用itertools将列表列表更改为一个列表,然后将其全部转换为float。

    heartdis = heartdis[5:]
    heartdis_flt = []
    heartdis2 = list(itertools.chain.from_iterable(heartdis))
    for item in heartdis2:
        heartdis_flt.append(float(item))
    print(heartdis_flt)

相关问题 更多 >