1

To parse

s="1,2,3,4_5,6,7,8"

as [[1,2,3,4],[5,6,7,8]]

I am currently using

import numpy as np
a=np.array([list(map(int,r.split(","))) for r in s.split("_")])

Is there a more pythonic or one-shot inbuilt way of doing this or am I on the right track here?
Python newbie.

2 Answers 2

2

Using list-comprehensions:

s="1,2,3,4_5,6,7,8"

a = np.array([[int(x) for x in r.split(',')] for r in s.split('_')])
Sign up to request clarification or add additional context in comments.

Comments

2

You can use np.genfromtxt:

from io import StringIO
import numpy as np

s="1,2,3,4_5,6,7,8"

np.genfromtxt(StringIO(s.replace("_", "\n")), delimiter=",")

array([[1., 2., 3., 4.],
       [5., 6., 7., 8.]])

2 Comments

Ah nice answer! Why is StringIO necessary here?
genfromtxt reads from a file-like object, which StringIO provides.

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.