Duplicate elements in a list

前端 未结 6 1128
滥情空心
滥情空心 2020-12-10 02:28

I have a list in Python:

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

I want to duplicate each element immediately next to the original.

6条回答
  •  误落风尘
    2020-12-10 03:05

    Here's a pretty easy way:

    sum(zip(l, l), tuple())
    

    It duplicates each item, and adds them to a tuple. If you don't want a tuple (as I suspect), you can call list on the the tuple:

    list(sum(zip(l, l), tuple()))
    

    A few other versions (that yield lists):

    list(sum(zip(l, l), ()))
    
    sum([list(i) for i in zip(l, l)], [])
    
    sum(map(list, zip(l, l)), [])
    

提交回复
热议问题