Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search a list of nested tuples of strings in python

Lets say I have a list x:

x=['alfa[1]', 'bravo', ('charlie[7]', 'delta[2]'), 'echo[3]']

I want to create a new list which both flattens and removes the bracketed number if the item has one. The result should be:

x_flattened_bases = ['alfa', 'bravo', 'charlie', 'delta', 'echo']

Here is what I currently have:

x_flattened_bases = []
for item in x:
    if isinstance(item, tuple):
        x_flattened_bases.extend([value.split('[')[0] for value in item)
    else:
        x_flattened_bases.append(item.split('[')[0])

There is only 1 level of nesting in the list.

like image 760
Darko Avatar asked Jan 14 '23 10:01

Darko


2 Answers

Something like this:

import collections
import re
def solve(lis):
  for element in lis:
    if isinstance(element, collections.Iterable) and not isinstance(element,str):
      for x in solve(element):
        yield re.sub(r"\[\d+\]",r"",x)
    else:
      yield re.sub(r"\[\d+\]",r"",element)

x=['alfa[1]', 'bravo', ('charlie[7]', 'delta[2]'), 'echo[3]']
print list(solve(x))

output:

['alfa', 'bravo', 'charlie', 'delta', 'echo']
like image 89
Ashwini Chaudhary Avatar answered Jan 17 '23 05:01

Ashwini Chaudhary


Flatten questions have been answered many times.

tl;dr use the horribly document ast module's flatten function

>>> from compiler.ast import flatten
>>> flatten([1,2,['dflkjasdf','ok'],'ok'])
[1, 2, 'dflkjasdf', 'ok', 'ok']

A one-liner that also strips out [] (assuming all child nodes are strings):

>>> from compiler.ast import flatten
>>>def flattenstrip(input): return [el[:el.find('[')] if el.find('[')!=-1 else el for el in  flatten(input)]
>>>flattenstrip(['alfa[1]', 'bravo', ('charlie[7]', 'delta[2]'), 'echo[3]'])
>>>['alfa', 'bravo', 'charlie', 'delta', 'echo']
like image 40
yoonkwon Avatar answered Jan 17 '23 07:01

yoonkwon