Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a text delimited string list item with multiple list items in a python list?

Tags:

python

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']
like image 578
rjmoggach Avatar asked Aug 02 '17 15:08

rjmoggach


People also ask

How do I replace a string in a list with elements?

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 .

How do you replace an item in a list with another item in Python?

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.

How do I replace a list to another list in Python?

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.


3 Answers

Another trick is first to join the list with underscores and then re-split it:

"_".join(mylist).split('_')
like image 115
Eugene Sh. Avatar answered Oct 20 '22 00:10

Eugene Sh.


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']
like image 29
AChampion Avatar answered Oct 20 '22 00:10

AChampion


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']
like image 40
cs95 Avatar answered Oct 20 '22 00:10

cs95