Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

Converting string series to float list in 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

and convert this to a float list

lsit = [5.2,5.6,5.3]

How can this be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...