How do you convert a list of strings to a list of floats using Python?

后端 未结 2 478
误落风尘
误落风尘 2021-01-29 09:01

If I have a list of strings:

[\'   3.2 4.5 7.8 9.2 4.3 4.7 5.2\',
\'   3.1 4.1 1.3 8.2 4.1 3.2 3.1\',
\'   3.1 4.2 5.7 3.2 4.1 3.0 1.9\']

How c

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-29 09:33

    Use

    l = ['   3.2 4.5 7.8 9.2 4.3 4.7 5.2',
    '   3.1 4.1 1.3 8.2 4.1 3.2 3.1',
    '   3.1 4.2 5.7 3.2 4.1 3.0 1.9']
    
    print( [map(float, i.strip().split()) for i in l] )
    

    Output:

    [[3.2, 4.5, 7.8, 9.2, 4.3, 4.7, 5.2], [3.1, 4.1, 1.3, 8.2, 4.1, 3.2, 3.1], [3.1, 4.2, 5.7, 3.2, 4.1, 3.0, 1.9]]
    
    • str.split() to split element by space
    • map(float, 'YOURLIST') to apply float on all elements.

提交回复
热议问题