4

I have a string array, for example:

a = ['123', '456', '789']

I want to split it to form a 2-dimension char array:

b = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

I'm using

[[element for element in line] for line in array]

to achieve my goal but found it not easy to read, is there any built-in function or any readable way to do it?

5 Answers 5

10

Looks like a job for map:

>>> a = ['123', '456', '789']
>>> map(list, a)
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

Relevant documentation:

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

Comments

4

you could do something like:

first_list = ['123', '456', '789']
other_weirder_list = [list(line) for line in first_list]

Your solution isn't that bad, but you might do something like this or the map suggestion by arashajii.

Comments

3

map(list, array) should do it.

Comments

1

You can use map:

>>> a
['123', '456', '789']
>>> map(list, a)
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

Although I really don't see why you'd need to do this (unless you plan on editing one specific character in the string?). Strings behave similarly to lists.

Comments

0

First I tried e.split(''), but I get ValueError: empty separator.

Try this:

a = ['123', '456', '789']
b = [list(e) for e in a]
b
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

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.