1

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?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
CrveniZg
  • 6,671
  • 2
  • 12
  • 8

3 Answers3

10

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.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

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',)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1
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']
Ivaylo
  • 2,082
  • 1
  • 13
  • 13