Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 235
user1589244 Avatar asked Aug 10 '12 05:08

user1589244


People also ask

How do I make a list of strings into a list in python?

The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int(x) for x in strings] . It iterates over all elements in the list and converts each list element x to an integer value using the int(x) built-in function.

How do I convert multiple strings to a list in python?

To do this we use the split() method in string. The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.

Can you have a list of list of lists in python?

Python provides an option of creating a list within a list. If put simply, it is a nested list but with one or more lists inside as an element. Here, [a,b], [c,d], and [e,f] are separate lists which are passed as elements to make a new list. This is a list of lists.


1 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

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]]
like image 50
jamylak Avatar answered Sep 24 '22 03:09

jamylak