在python中将字符串系列转换为浮点列表
问题描述:
我对编程很陌生,所以我希望这个问题足够简单.
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
并将其转换为浮点列表
lsit = [5.2,5.6,5.3]
如何做到这一点?
答
尝试列表理解:
s = '5.2 5.6 5.3'
floats = [float(x) for x in s.split()]
在 Python 2.x 中也可以使用 map 来完成:
In Python 2.x it can also be done with map:
floats = map(float, s.split())
请注意,在 Python 3.x 中,第二个版本返回的是地图对象而不是列表.如果您需要一个列表,您可以通过调用 list
将其转换为列表,或者只使用列表理解方法.
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.