Given a list:
mylist = ['dog', 'cat', 'mouse_bear', 'lion_tiger_rabbit', 'ant']
I'd like a one-liner to return a new list:
['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.
The difference is that the first option copies the elements of newgamewords and assigns it to gamewords. The second option just assigns a reference of newgamewords to gamewords. Using the second version, you would change the original newgamewords-list if you changed gamewords.
Another trick is first to join the list with underscores and then re-split it:
"_".join(mylist).split('_')
Just use 2 for
clauses in your comprehension, e.g.:
>>> mylist = ['dog', 'cat', 'mouse_bear', 'lion_tiger_rabbit', 'ant']
>>> [animal for word in mylist for animal in word.split('_')]
['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
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']
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