Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List with duplicated values and suffix

I have a list, a:

a = ['a','b','c'] 

and need to duplicate some values with the suffix _ind added this way (order is important):

['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind'] 

I tried:

b = [[x, x + '_ind'] for x in a] c = [item for sublist in b for item in sublist] print (c) ['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind'] 

Is there some better, more pythonic solution?

like image 665
jezrael Avatar asked Jul 15 '17 19:07

jezrael


People also ask

Can a list have repeated values?

What are duplicates in a list? If an integer or string or any items in a list are repeated more than one time, they are duplicates.

Can a list have duplicate values in Python?

Python list can contain duplicate elements.


1 Answers

You could make it a generator:

def mygen(lst):     for item in lst:         yield item         yield item + '_ind'  >>> a = ['a','b','c'] >>> list(mygen(a)) ['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind'] 

You could also do it with itertools.product, itertools.starmap or itertools.chain or nested comprehensions but in most cases I would prefer a simple to understand, custom generator-function.


With python3.3, you can also use yield from—generator delegation—to make this elegant solution just a bit more concise:

def mygen(lst):     for item in lst:         yield from (item, item + '_ind') 
like image 97
MSeifert Avatar answered Oct 08 '22 20:10

MSeifert