How to convert a delimited string back to list in Python

Viewed 43

I have a delimited String as follows,

list1 = ['[107 207]', '[110 245]', '[115 282]', '[120 320]']

How can I convert this back to list in Python? The converted list should look like this:

[[107 207]
[110 245]
[115 282]
[120 320]]

I have tried list1 = list1.split(","). But, when I print list[0] I'm getting this,

['[107 207]'

instead of getting this,

[107 207]

Also, trying list1 = [int(e) for e in list1.split(',')] gave me an error as follows:

"invalid literal for int() with base 10: \"['[107 207]'\""
2 Answers

One option, using a nested list comprehension along with re.findall to extract all digits:

list1 = ['[107 207]', '[110 245]', '[115 282]', '[120 320]']
output = [[int(y) for y in re.findall(r'\d+', x)] for x in  list1]
print(output)

This prints:

[[107, 207], [110, 245], [115, 282], [120, 320]]

There is probably a way to do this without invoking regex, but the int() cast seems mandatory to me, given that the input numbers start off inside a string.

You could strip the brackets off of the ends of each element. This method could probably be cleaner, but it is done in pure Python with no imports or regex.

input = ['[107 207]', '[110 245]', '[115 282]', '[120 320]']

output = [[int(ii) for ii in i.lstrip("[").rstrip("]").split(" ")] for i in input]

This returns exactly what you wanted:

[[107, 207], [110, 245], [115, 282], [120, 320]]

Here's a human-readable form of the code to help visualize what is going on:

output = []

for item in input:
    itemString = item.lstrip("[")
    itemString = itemString.rstrip("]")
    itemList = itemString.split(" ")
    itemNumbers = [int(ii) for ii in itemList]
    output.append(itemNumbers)
Related