如何在整数列表中找到重复项并创建重复项的另一个列表?
当前回答
下面是一个快速生成器,它使用dict将每个元素存储为一个带有布尔值的键,用于检查是否已经产生了重复项。
对于所有元素都是可哈希类型的列表:
def gen_dupes(array):
unique = {}
for value in array:
if value in unique and unique[value]:
unique[value] = False
yield value
else:
unique[value] = True
array = [1, 2, 2, 3, 4, 1, 5, 2, 6, 6]
print(list(gen_dupes(array)))
# => [2, 1, 6]
对于可能包含列表的列表:
def gen_dupes(array):
unique = {}
for value in array:
is_list = False
if type(value) is list:
value = tuple(value)
is_list = True
if value in unique and unique[value]:
unique[value] = False
if is_list:
value = list(value)
yield value
else:
unique[value] = True
array = [1, 2, 2, [1, 2], 3, 4, [1, 2], 5, 2, 6, 6]
print(list(gen_dupes(array)))
# => [2, [1, 2], 6]
其他回答
def removeduplicates(a):
seen = set()
for i in a:
if i not in seen:
seen.add(i)
return seen
print(removeduplicates([1,1,2,2]))
试试这个检查副本
>>> def checkDuplicate(List):
duplicate={}
for i in List:
## checking whether the item is already present in dictionary or not
## increasing count if present
## initializing count to 1 if not present
duplicate[i]=duplicate.get(i,0)+1
return [k for k,v in duplicate.items() if v>1]
>>> checkDuplicate([1,2,3,"s",1,2,3])
[1, 2, 3]
我注意到大多数解决方案的复杂度为O(n * n),对于大型列表来说非常缓慢。所以我想分享一下我写的函数,它支持整数或字符串,在最好的情况下是O(n)。对于一个包含10万个元素的列表,最上面的解决方案需要超过30秒,而我的解决方案只需0.12秒
def get_duplicates(list1):
'''Return all duplicates given a list. O(n) complexity for best case scenario.
input: [1, 1, 1, 2, 3, 4, 4]
output: [1, 1, 4]
'''
dic = {}
for el in list1:
try:
dic[el] += 1
except:
dic[el] = 1
dupes = []
for key in dic.keys():
for i in range(dic[key] - 1):
dupes.append(key)
return dupes
list1 = [1, 1, 1, 2, 3, 4, 4]
> print(get_duplicates(list1))
[1, 1, 4]
或者获得唯一的副本:
> print(list(set(get_duplicates(list1))))
[1, 4]
方法1:
list(set([val for idx, val in enumerate(input_list) if val in input_list[idx+1:]]))
解释: [val for idx, val in enumerate(input_list) if val in input_list[idx+1:]]是一个列表推导式,它返回一个元素,如果该元素从当前位置存在,则在列表中返回下标。
例子: input_list =[3 42 42岁,31日,31日,31日,31日,5日,6日6日6日6日6日,7日,42)
从索引为0的列表第一个元素42开始,它检查元素42是否存在于input_list[1:]中(即从索引1到列表末尾)。 因为42存在于input_list[1:]中,它将返回42。
然后它转到下一个索引为1的元素31,并检查元素31是否存在于input_list[2:](即从索引2到列表末尾), 因为31存在于input_list[2:]中,它将返回31。
类似地,它遍历列表中的所有元素,只将重复/重复的元素返回到列表中。
然后,因为列表中有重复项,我们需要从每个重复项中选择一个,即从重复项中删除重复项,为此,我们调用python内置的名为set()的函数,它会删除重复项,
然后我们就得到了一个集合,而不是一个列表,因此为了将集合转换为列表,我们使用类型转换,list(),它将元素集转换为列表。
方法2:
def dupes(ilist):
temp_list = [] # initially, empty temporary list
dupe_list = [] # initially, empty duplicate list
for each in ilist:
if each in temp_list: # Found a Duplicate element
if not each in dupe_list: # Avoid duplicate elements in dupe_list
dupe_list.append(each) # Add duplicate element to dupe_list
else:
temp_list.append(each) # Add a new (non-duplicate) to temp_list
return dupe_list
解释: 首先,我们创建两个空列表。 然后继续遍历列表中的所有元素,以查看temp_list(最初为空)中是否存在该元素。如果它不在temp_list中,则使用append方法将它添加到temp_list中。
如果它已经存在于temp_list中,这意味着列表中的当前元素是重复的,因此我们需要使用append方法将它添加到dupe_list中。
一个非常简单的解决方案,但是复杂度是O(n*n)。
>>> xs = [1,2,3,4,4,5,5,6,1]
>>> set([x for x in xs if xs.count(x) > 1])
set([1, 4, 5])
推荐文章
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节
- 不区分大小写列表搜索
- TypeError: ` NoneType `对象在Python中不可迭代
- 如何在Vim注释掉一个Python代码块
- python标准库中的装饰符(特别是@deprecated)
- 如何从外部访问本地Django web服务器
- 删除字符串的最后3个字符
- 在python中执行no-op的标准方法是什么?
- 如何从生成器构建numpy数组?
- 什么时候我应该(不)想要在我的代码中使用熊猫apply() ?
- 数据类vs类型。NamedTuple主要用例