I have list like
['a', 'pnp', 'a|pnp', 'lab2|pnp']
and I want to split them and have this
['a', 'pnp', 'a', '|', 'pnp', 'lab2', '|', 'pnp']
Any ideas?
I have list like
['a', 'pnp', 'a|pnp', 'lab2|pnp']
and I want to split them and have this
['a', 'pnp', 'a', '|', 'pnp', 'lab2', '|', 'pnp']
Any ideas?
Here is one way:
>>> l = ['a', 'pnp', 'a|pnp', 'lab2|pnp']
>>> list(itertools.chain(*(re.split("([|])", el) for el in l)))
['a', 'pnp', 'a', '|', 'pnp', 'lab2', '|', 'pnp']
For an explanation of re.split("([|])", ...), see In Python, how do I split a string and keep the separators?
itertools.chain() simply chains the results together, and list() converts the resulting iterable into a list.
You can use itertools.chain.from_iterable with str.partition here:
>>> from itertools import chain
>>> lst = ['a', 'pnp', 'a|pnp', 'lab2|pnp']
>>> list(chain.from_iterable(x.partition('|') if '|' in x else [x] for x in lst))
['a', 'pnp', 'a', '|', 'pnp', 'lab2', '|', 'pnp']
#or
>>> list(chain.from_iterable(filter(None, x.partition('|')) for x in lst))
['a', 'pnp', 'a', '|', 'pnp', 'lab2', '|', 'pnp']
Here itertools.chain.from_iterable is used for flattening the list of lists(or tuples), and str.partition is used to split the string at the sep |:
>>> 'lab2|pnp'.partition('|')
('lab2', '|', 'pnp')
For items with the sep not present you'll have to use either filter or an conditional expression to handle the empty values of sep and tail:
>>> 'abc'.partition('|')
('abc', '', '')
>>> filter(None, 'abc'.partition('|'))
('abc',)
a = ['a', 'pnp', 'a|pnp', 'lab2|pnp']
b = list()
for items in a:
f = items.split('|')
for z in range(len(f)-1):
b.append(f[z])
b.append('|')
b.append(f[-1])
print(b)
['a', 'pnp', 'a', '|', 'pnp', 'lab2', '|', 'pnp']