在python中将字符串系列转换为浮点列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4004550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting string series to float list in python
提问by Michael F
I am quite new to programing so I hope this question is simple enough.
我对编程很陌生,所以我希望这个问题足够简单。
I need to know how to convert a string input of numbers separated by spaces on a single line:
我需要知道如何在一行中转换由空格分隔的数字字符串输入:
5.2 5.6 5.3
and convert this to a float list
并将其转换为浮点列表
lsit = [5.2,5.6,5.3]
How can this be done?
如何才能做到这一点?
回答by Mark Byers
Try a list comprehension:
尝试列表理解:
s = '5.2 5.6 5.3'
floats = [float(x) for x in s.split()]
In Python 2.x it can also be done with map:
在 Python 2.x 中,也可以使用 map 来完成:
floats = map(float, s.split())
Note that in Python 3.x the second version returns a map object rather than a list. If you need a list you can convert it to a list with a call to list, or just use the list comprehension approach instead.
请注意,在 Python 3.x 中,第二个版本返回的是地图对象而不是列表。如果您需要一个列表,您可以通过调用 将其转换为一个列表list,或者只使用列表理解方法。

