Duplicate element in python list

2019-02-12 02:05发布

问题:

I have a list in Python:

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

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

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

The order of the elements should be preserved.

回答1:

>>> l = ['a', 'c', 'e', 'b']
>>> [x for pair in zip(l,l) for x in pair]
['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']

Or

>>> from itertools import repeat
>>> [x for item in l for x in repeat(item, 2)]
['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']


回答2:

This is old but I can't see the straightforward option here (IMO):

[ item for item in l for repetitions in range(2) ]

So for the specific case:

>>> l = ['a', 'c', 'e', 'b']
l = ['a', 'c', 'e', 'b']
>>> [ i for i in l for r in range(2) ]
[ i for i in l for r in range(2) ]
['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']
>>> 

And generalizing:

[ item for item in l for _ in range(r) ] 

Where r is the quantity of repetitions you want.

So this has a O(n.r) space and time complexity, is short, with no dependencies and also idiomatic.



回答3:

import itertools

ll = list(itertools.chain.from_iterable((e, e) for e in l))

At work:

>>> import itertools
>>> l = ['a', 'c', 'e', 'b']
>>> ll = list(itertools.chain.from_iterable((e, e) for e in l))
>>> ll
['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']

As Lattyware pointed out, in case you want more than just double the element:

from itertools import chain, repeat

ll = list(chain.from_iterable(repeat(e, 2) for e in l))


回答4:

Try this

for i in l:
    ll.append(i)
    ll.append(i)

Demo

It will just do your work but it's not an optimized way of doing this.

use the ans. posted by @Steven Rumbalski



回答5:

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)), [])