在python中将字符串系列转换为浮点列表 [英] Converting string series to float list in python

查看:68
本文介绍了在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.

这篇关于在python中将字符串系列转换为浮点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆