List with duplicated values and suffix

前端 未结 6 1463
抹茶落季
抹茶落季 2020-11-30 02:48

I have a list, a:

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

and need to duplicate some values with the suffix _ind added this way (

6条回答
  •  孤城傲影
    2020-11-30 03:38

    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')
    

提交回复
热议问题