【问题标题】:How to convert string numbers to list? [duplicate]如何将字符串数字转换为列表? [复制]
【发布时间】:2019-10-16 04:05:26
【问题描述】:

我有一串这样的数字

i = '584,569.2,11515,632'

想把它转换成这样的数字列表。

[584,569.2,11515,632]

【问题讨论】:

  • list(map(float,i.split(',))) ?
  • [float(n) for n in i.split(',')] 应该可以解决问题。
  • 太棒了!祝你好运,如果遇到困难,请就你尝试和研究过的内容提出问题
  • [int(x) if x.is_integer() else x for x in map(float, i.split(','))] if int vs float dtypes 很重要

标签: python


【解决方案1】:

你可以这样做:

i = '584,569.2,11515,632'
numbers = list(map(float, i.split(',')))
print(numbers)

输出:

[584.0, 569.2, 11515.0, 632.0]

另外,作为 Chris A pointed out,如果 intfloat 之间的区别很重要,您可以使用 is_integer()

numbers = [int(x) if x.is_integer() else x for x in map(float, i.split(','))]

输出:

[584, 569.2, 11515, 632]

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 2012-05-23
    • 2015-08-01
    • 1970-01-01
    • 2023-03-07
    • 2013-07-07
    • 2023-01-04
    相关资源
    最近更新 更多