Search code examples
pythonpython-3.xlist-comprehension

How to transform a string into a list of char and int using a list comprehension in Python


Given the following string:

"[10,20]"

I want to create the following list using a list comprehension in Python:

['[', 10, ',', 20, ']']

Being 10 and 20 integers and the rest of the elements in the list chars.

I assume that I would need a to use something similar to what itertools.groupby(iterable, key=None) provides:

Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.

However Python's group by returns an iterator with consecutive keys and groups. In my case the keys would change so I guess I'd need a similar iterator that returns the groups based on a filter. Any ideas?


Solution

  • Group by whether this character is numeric or not. This can be done using the str.isnumeric function as the key argument to groupby().

    s = "[10,20]"
    g = itertools.groupby(s, key=str.isnumeric)
    

    Then, for the True groups, convert it to an integer. Leave False groups as-is. Since the values of the groupby are iterators where each element is a separate character, you need to join it with "" to convert it into a single string, and optionally convert that string to an integer.

    lst = [int("".join(chars)) if is_numeric else "".join(chars) for is_numeric, chars in g]
    

    Which gives:

    ['[', 10, ',', 20, ']']
    

    In one line:

    lst = [                  int("".join(chars)) 
          if is_numeric else "".join(chars) 
          for is_numeric, chars in itertools.groupby(s, key=str.isnumeric)
          ]