Search code examples
pythonstringlistsplitparentheses

Split a list into pairs using python


I have a list/string. And I would like to split it into pairs and separate them by parenthesis in the same list as output. How do I do that?

What I tried so far?

ip='MDSYS.SDO_GEOMETRY(2003, NULL, NULL, MDSYS.SDO_ELEM_INFO_ARRAY(1, 1003, 1), MDSYS.SDO_ORDINATE_ARRAY(22027, 22943.23, 22026, 22939, 22025, 22936, 22025.09, 22932, 22027, 22929, 22030, 22926)'
split_string_1 = "MDSYS.SDO_ORDINATE_ARRAY("
split_string_2 = ")"

data = list(map(int, ip.split(split_string_1)[1].split(split_string_2)[0].split(", ")))

result = list(zip(data[:-1], data[1:]))

I get an error saying ValueError: invalid literal for int() with base 10: '22943.23' How do I solve this?

Desired output:

[(22027, 22943.23), (22026, 22939), (22025, 22936), (22025.09, 22932), (22027, 22929), (22030, 22926)]

Solution

  • Use regex pattern ('\([0-9., ]+\) which will give you all tuples containing interger/float, convert string to tuple using ast.literal_eval(). Finally get list of tuples using list(zip(out[::2], out[1::2])

    import ast
    import re
    
    out = re.findall('\([0-9., ]+\)', ip)[-1]
    out = ast.literal_eval(out)
    out = list(zip(out[::2], out[1::2])
    print(out)
    
    [(22027, 22943.23),
     (22026, 22939),
     (22025, 22936),
     (22025.09, 22932),
     (22027, 22929),
     (22030, 22926)]