user1589244
user1589244

Reputation: 445

Python: string to a list of lists

I'm new to python and confused about converting a string to a list. I'm unsure how to create a list within a list to accomplish the following:

Ex.

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

I'm trying to use split() to create a data structure, my_data, so that when I input

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

Stuck: This is what I did at first:

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

And I know that you can't split a list so I split() the string first but I don't know how to convert the strings within the new list into a list in order to me to get the right output.

Upvotes: 10

Views: 13695

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

>>> 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(','))), as map() returns a map object in python 3.x

Upvotes: 2

jamylak
jamylak

Reputation: 133514

>>> 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

Maybe you also want to convert each digit (still strings) 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]]

Upvotes: 23

Related Questions