Python: string to list of lists

I am new to python and am confused about converting a string to a list. I am not sure how to create a list in a list to do the following:

Ex.

string = '2,4,6,8|10,12,14,16|18,20,22,24' 

I am trying to use split () to create my_data data structure so that when I enter

 print my_data[1][2] #it should return 14 

Stuck: This is what I did first:

 new_list = string.split('|') #['2,4,6,8', '10,12,14,16,', '18,20,22,24'] 

And I know that you cannot split the list, so at first I split() , but I do not know how to convert the lines from the new list to the list so that I can get the correct output.

+4
source share
2 answers
 >>> text = '2,4,6,8|10,12,14,16|18,20,22,24' >>> my_data = [x.split(',') for x in text.split('|')] >>> my_data [['2', '4', '6', '8'], ['10', '12', '14', '16'], ['18', '20', '22', '24']] >>> print my_data[1][2] 14 

You might also want to convert each digit (fixed lines) to int , in which case I would do this:

 >>> [[int(y) for y in x.split(',')] for x in text.split('|')] [[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]] 
+16
source
 >>> strs = '2,4,6,8|10,12,14,16|18,20,22,24' >>> strs1=strs.split('|') >>> [map(int,x.split(',')) for x in strs1] [[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]] 

Note: for python 3.x use list(map(int,x.split(','))) since map() returns a map object in python 3.x

+2
source

All Articles