【问题标题】:I would like to convert data type from within a nested list我想从嵌套列表中转换数据类型
【发布时间】:2019-12-14 20:20:36
【问题描述】:

使用 Jupyter Notebooks/python 3.x;我一直在试图弄清楚如何将字符串转换为列表中的浮点数。我不知道如何最好地做到这一点,任何建议将不胜感激。我已经转换了单个项目,但是当我尝试将数据保存回测试列表时遇到了各种错误。

my_test_list=[]
my_test_list= [[ '7','8','9','10','11'],['12','13','14','15','16']]

for i in my_test_list:
    for x in i:
        try:
            x=float(x)
            print(x)
        except ValueError:
            pass

print(my_test_list)

产生结果:

7.0
8.0
9.0
10.0
11.0
12.0
13.0
14.0
15.0
16.0
[['7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16']]

我希望print(my_test_list) 产生结果:

[[7.0, 8.0, 9.0, 10.0, 11.0], [12.0, 13.0, 14.0, 15.0, 16.0]]

【问题讨论】:

  • 所有的innerlists长度都一样吗?
  • 列表可以嵌套多深?
  • 内部列表长度不同;列表将不再嵌套。

标签: python return return-value nested-lists


【解决方案1】:

这一行就可以实现

test = [['7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16']]


test = [[float(x) for x in l] for l in test]

【讨论】:

  • 我正在使用 try/except 因为它也可能有实际的单词而不仅仅是数字。我忘记了那部分,我非常专注于如何让我的浮点数从我的 for 循环中恢复。
【解决方案2】:

使用 numpy 真的又快又简单

import numpy
print(numpy.array([[ '7','8','9','10','11'],['12','13','14','15','16']],dtype=float))

【讨论】:

    【解决方案3】:

    我同意 Nuno Palma 的回答,但没有解释为什么此代码有效而您的代码无效。简单地说,你的代码:

    for i in my_test_list:
    for x in i:
        try:
            x=float(x)
            print(x)
        except TypeError:
            pass
    

    从不实际将转换后的 x 保存到 my_test_list。虽然提供的答案更加简洁,但您的代码可以通过简单的添加来工作:

    output_list = []
    for i in my_test_list:
    for x in i:
        try:
            x=float(x)
            print(x)
            output_list[i].append(x)
        except TypeError:
            pass
    

    接受的答案本质上是对此的简写。

    【讨论】:

    • 谢谢!根据一位朋友在电话中告诉我的建议,我最终不得不使用 .index() 来让它工作。
    猜你喜欢
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2018-03-23
    • 1970-01-01
    • 2020-06-22
    相关资源
    最近更新 更多