I have the list of strings:
['[12 9 15]','[98 12 18]','[56 45 45]']
and I want to convert it to
[[12,9,15],[98,12,18],[56,45,45]]
I have the list of strings:
['[12 9 15]','[98 12 18]','[56 45 45]']
and I want to convert it to
[[12,9,15],[98,12,18],[56,45,45]]
You can use split
inside a list comprehension to do this.
As [1 2 3]
is not the proper representation of a python list in a string, we can remove the brackets to get '1 2 3'
which on splitting becomes ['1', '2', '3']
. This can be easily converted to a integer nested list by casting it to an int using the int
callable.
>>> l = ['[12 9 15]','[98 12 18]','[56 45 45]']
>>> [[int(j) for j in i[1:-1].split()] for i in l]
[[12, 9, 15], [98, 12, 18], [56, 45, 45]]
For further reading What does "list comprehension" mean? How does it work and how can I use it?
Your strings [12 9 15]
aren't formatted like python lists (commas are missing). You've got a couple options depending on how robust your parser needs to be:
import ast
out_list = []
for string_list in list_of_strings:
list_repr = ','.join(string_list.split())
out_list.append(ast.literal_eval(list_repr))
This will work so long as you don't have any inner strings formatted like:
'[ 12 9, 5]
(the leading space will mess it up)
I think that probably the most robust parser that I can think of is to remove the [
and ]
and them parse it yourself:
out_list = []
for string_list in list_of_strings:
str_items = string_list.replace('[', '').replace(']', '')
out_list.append([int(item) for item in str_items.split()])
As long as the strings are fairly regular, this should work:
>>> x = ['[12 9 15]','[98 12 18]','[56 45 45]']
>>> x = [[int(i) for i in string.strip('[]').split()] for string in x]
>>> x
[[12, 9, 15], [98, 12, 18], [56, 45, 45]]
Use a regular expression
[map(int, re.findall('\d+', item)) for item in x]
In case it is not always well-formated.
>>> import re
>>> [map(int, re.findall('\d+', item)) for item in x]
[[12, 9, 15], [98, 12, 18], [56, 45, 45]]
The simpler the solution, the better it is for others to understand.
Well here is my solution:
list_of_strings = ['[12 9 15]','[98 12 18]','[56 45 45]']
list_of_lists = [map(int, x[1:-1].split()) for x in list_of_strings]
So I using list-comprehension here. The 'map' function returns a list. The code x[1:-1].split()
will split each string on space character(s) and the each string token would then be converted to 'int' which is the function I've passed to the map function.
Need more explanation over my code?
Please check if this is helpful.
>>> x = ['[12 9 15]','[98 12 18]','[56 45 45]']
>>> print eval(str([ item.replace(" ",",") for item in x ]).replace("'", ''))
[[12, 9, 15], [98, 12, 18], [56, 45, 45]]