Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string array to 2-dimension char array in python

Tags:

python

arrays

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?

like image 778
waitingkuo Avatar asked Dec 02 '22 20:12

waitingkuo


2 Answers

Looks like a job for map:

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

Relevant documentation:

  • map
  • list
like image 92
arshajii Avatar answered Dec 24 '22 00:12

arshajii


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.

like image 22
Andbdrew Avatar answered Dec 24 '22 01:12

Andbdrew