"TypeError: float argument must be a string or a number, not a list."将字符串列表转换为浮点数列表



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

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

我找到了可以工作的东西。 我使用迭代工具将列表列表更改为一个列表,然后将其全部转换为浮点数。

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

就像@utdemir评论的那样,你的代码的问题在于你把列表当作一个字符串。你确实可以使用itertools.chain,但也许你想首先改变你从heartdis阅读的方式。我不知道您是如何阅读CSV文件的,但是如果您使用的是csv模块,我认为您不应该将列表列表作为输出。无论如何,在我看来,您应该检查一下。

相关内容

最新更新