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.
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With