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?
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.
Python list can contain duplicate elements.
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')
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