Given a list:
mylist = [\'dog\', \'cat\', \'mouse_bear\', \'lion_tiger_rabbit\', \'ant\']
I\'d like a one-liner to return a new list:
One-liners are over-rated. Here's a solution using a "traditional" for
loop.
mylist = ['dog', 'cat', 'mouse_bear', 'lion_tiger_rabbit', 'ant']
out = []
for s in mylist:
if '_' in s:
out.extend(s.split('_'))
else:
out.append(s)
print(out)
output
['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
This also works:
out = []
for s in mylist:
out.extend(s.split('_'))
It's shorter, but I think the previous version is clearer.
You can try this:
from itertools import chain
mylist = ['dog', 'cat', 'mouse_bear', 'lion_tiger_rabbit', 'ant']
new_list = list(chain(*[[i] if "_" not in i else i.split("_") for i in mylist]))
Output:
['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
mylist = ['dog', 'cat', 'mouse_bear', 'lion_tiger_rabbit', 'ant']
animals = [a for item in mylist for a in item.split('_')]
print (animals)
This is not a one liner, but is nevertheless a valid option to consider if you want to return a generator:
def yield_underscore_split(lst):
for x in lst:
yield from x.split('_')
>>> list(yield_underscore_split(mylist))
['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
Original answer valid only for versions Python 3.3-3.7, kept here for interested readers. Do not use!
>>> list([(yield from x.split('_')) for x in l])
['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
Split each item into sublists and flatten them:
[item for sublist in mylist for item in sublist.split("_")]
what I would actually do:
newlist = []
for i in mylist:
newlist += i.split('_')