0

I have a string of the form:

"77.1234 15.3456,79.8765 15.6789,81.9876 16.0011"

I need to convert it to the form:

[[77.1234,15.3456],[79.8765,15.6789],[81.9876,16.0011]]

Can someone help me to accomplish this using the replace() function in python? If it cannot be achieved with that, then what other function provided by python can be used?

Thank you.

4 Answers 4

6

Use a list comprehension with map:

>>> s = "77.1234 15.3456,79.8765 15.6789,81.9876 16.0011"
>>> [list(map(float, x.split())) for x in s.split(',')]
[[77.1234, 15.3456], [79.8765, 15.6789], [81.9876, 16.0011]]

In Python 2 you can remove the list() call around map.

Sign up to request clarification or add additional context in comments.

Comments

3

Use list comprehension,

First split the string by comma, then split each element of the new list by space and cast it into a float type.

>>> x = "77.1234 15.3456,79.8765 15.6789,81.9876 16.0011"
>>> [[float(j) for j in i.split()] for i in x.split(',')]
[[77.1234, 15.3456], [79.8765, 15.6789], [81.9876, 16.0011]]

It achieves the same result as this:

>>> x = "77.1234 15.3456,79.8765 15.6789,81.9876 16.0011"
>>> ls = []
>>> for i in x.split(','):
...     for j in i.split():
...             ls.append(float(j))
... 
>>> ls
[77.1234, 15.3456, 79.8765, 15.6789, 81.9876, 16.0011]

Comments

2

replace will not convert strings to floating point numbers. You need to call float to do that.

One option would be:

In [1]: s = "77.1234 15.3456,79.8765 15.6789,81.9876 16.0011"

In [2]: [[float(n) for n in p.split()] for p in s.split(',')]
Out[2]: [[77.1234, 15.3456], [79.8765, 15.6789], [81.9876, 16.0011]]

Comments

2
>>> [map(float, x.split()) for x in s.split(',')]
[[77.1234, 15.3456], [79.8765, 15.6789], [81.9876, 16.0011]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.