Search code examples
stringlistinteger-arithmetic

How do I split list of strings to list of strings in a list?


For example,

list1 = ['1 + 1', '2 + 5']

becomes,

split_list = [[1, +, 1],[2, +, 5]]

I tried

split_list = [item.split('_') for item in list1]

which returned [['1 + 1'], ['2 + 5']]. I'm trying to build a function that will rewrite, a list of simple arithmetic problems written in strings, into list of integers and math operators. Maybe I'm going about this wrong way I don't know.


Solution

  • list1 = ['1 + 1', '2 + 5']
    [e.split() for e in list1]
    

    Result:

    [['1', '+', '1'], ['2', '+', '5']]
    

    If you want to parse an expression without separators, you need to use standart library re module, for example so:

    parse = lambda f: [s.strip() for s in re.search(r'(\d+)(\D+)(\d+)', f).groups()]
    [parse(e) for e in list1]