Split a string to a list of integers

Viewed 64

I am working on Google's OR-Tools for solving a simple VRP problem. I need to plot the solution. So, I parse print_solution() function to return a dictionary of tours. Now, I have got a string list like this

tour = [' 0 ->  14 ->  15 ->  19 ->  1 ->  13 ->  5 ->  10 ->  20 ->  3 ->  7 ->  6 ->  16 ->  4 ->  9 ->  2 ->  17 ->  11 ->  12 ->  8 ->  18 -> 0']

Could someone please help me to obtain only the integers from this list?

2 Answers
x = tour.split('->')
int_list = [int(num.strip()) for num in x]

The first provided answer has some issues, but it does almost work. The idea behind it is sound. See the comments on the answer for an explanation of the issues I see.

I would do this differently, so that what the split results in is purely digits rather than digits with spaces on either side that then have to be dealt with separately. That is, I'd cause the spaces to been seen as being parts of the delimiters. So I'd do this instead:

import re

tour = [' 0 ->  14 ->  15 ->  19 ->  1 ->  13 -> 5 ->  10 ->  20 ->  3 ->  7 ->  6 ->  16 ->  4 ->  9 ->  2 ->  17 ->  11 ->  12 ->  8 ->  18 -> 0']

x = [int(digits) for digits in re.split(r'\s*->\s*', tour[0])]

print(x)

Result:

[0, 14, 15, 19, 1, 13, 5, 10, 20, 3, 7, 6, 16, 4, 9, 2, 17, 11, 12, 8, 18, 0]

This code will work regardless of if int() deals correctly with its argument being padded with spaces, since the spaces have already been stripped away.

Related