【问题标题】:"TypeError: float argument must be a string or a number, not a list." converting a list of strings to a list of floats“TypeError:浮点参数必须是字符串或数字,而不是列表。”将字符串列表转换为浮点数列表
【发布时间】:2014-11-29 07:35:36
【问题描述】:

我正在尝试将字符串列表转换为浮点数列表。我尝试过列表理解、映射,并简单地将其写在 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 不是list,它是list of list of something
  • 我明白了,所以我需要先将列表更改为字符串。谢谢!
  • 一旦您实际向其提供浮点字符串列表,Map 就会正常工作。 print(list(map(float, ['1.2', '3', '3.1459']))) 产生 [1.2, 3.0, 3.1459]

标签: python python-3.x


【解决方案1】:

我发现了一些可行的方法。我使用 itertools 将列表列表更改为一个列表,然后将其全部转换为浮点数。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 2013-08-11
      • 2019-10-31
      • 2017-09-26
      • 2019-03-31
      相关资源
      最近更新 更多