简体   繁体   English

如何使用Python将字符串列表转换为浮点列表?

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

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 can I convert it to a list of floats so my result looks something like this: 如何将其转换为浮点数列表,因此我的结果如下所示:

[[3.2, 4.5, 7.8, 9.3, 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]]

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 str.split()用于按空间拆分元素
  • map(float, 'YOURLIST') to apply float on all elements. map(float, 'YOURLIST')将float应用于所有元素。

You can use below code: 您可以使用以下代码:

numbers = ['   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([[float(number) for number in number_list.split()] for number_list in numbers])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Python中,如何将列表列表中的字符串转换为其他类型,如整数,浮点数,布尔值等? - In Python how do you convert strings in a list of list to other types, such as ints, floats, booleans, etc? 如何将字符串列表转换为浮点数? - How to convert list of strings to floats? 无法使用 float() 将字符串列表转换为 python 中的浮点列表 - Cannot convert list of strings to list of floats in python using float() 如何将整数和字符串列表更改为 python 中的整数和浮点数列表? - How do you change a list of integers and strings into a list of integers and floats in python? 如何将浮点数元组列表转换为 Python 中的字符串列表? - How to convert a list of tuples of floats to list of strings in Python? 如何在Python 3中将字符串列表转换为单独的字符串? - How do you convert a list of strings to separate strings in Python 3? 如何将列表列表中的所有字符串转换为浮点数 - How to convert all the strings in a list of a list to floats Python:将字符串列表转换为空/无浮点数 - Python : Convert list of strings to floats with empty/none 如何将由整数和浮点数组成的列表中的字符串列表转换为整数和浮点数? - How do I convert a list of strings in a list composed of ints and floats to both ints and floats? 如何将字符串的 ndarray 列表转换为浮点数 - How to convert a list of ndarray of strings into floats
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM