Python 列表中的重复元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14878538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Duplicate elements in a list
提问by tesla1060
I have a listin Python:
我list在 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.
应保留元素的顺序。
采纳答案by Steven Rumbalski
>>> 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']
回答by StoryTeller - Unslander Monica
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:
正如 Lattyware 指出的那样,如果您想要的不仅仅是两倍的元素:
from itertools import chain, repeat
ll = list(chain.from_iterable(repeat(e, 2) for e in l))
回答by Arpit
回答by Zach Gates
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 liston the the tuple:
它复制每个项目,并将它们添加到一个元组中。如果你不想要元组(我怀疑),你可以调用list元组:
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)), [])
回答by olivecoder
This is old but I can't see the straightforward option here (IMO):
这是旧的,但我在这里看不到直接的选项(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.
其中 r 是您想要的重复次数。
So this has a O(n.r) space and time complexity, is short, with no dependencies and also idiomatic.
所以这有一个 O(nr) 空间和时间复杂度,很短,没有依赖关系,也是惯用的。
回答by Valentin Fabianski
Pandas gives a method for duplicated elements:
Pandas 给出了一种处理重复元素的方法:
import pandas as pd
l = pd.Series([2, 1, 3, 1])
print(l.duplicated())
>>>0 False
1 False
2 False
3 True
dtype: bool
print('Has list duplicated ? :', any(l.duplicated()))
>>>Has list duplicated ? : True

