如何在整数列表中找到重复项并创建重复项的另一个列表?
当前回答
在列表中使用list.count()方法查找给定列表的重复元素
arr=[]
dup =[]
for i in range(int(input("Enter range of list: "))):
arr.append(int(input("Enter Element in a list: ")))
for i in arr:
if arr.count(i)>1 and i not in dup:
dup.append(i)
print(dup)
其他回答
下面是一个快速生成器,它使用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]
我没有看到一个纯粹使用迭代器的解决方案,所以我们开始吧
这需要对列表进行排序,这可能是这里的缺点。
a = [1,2,3,2,1,5,6,5,5,5]
a.sort()
set(map(lambda x: x[0], filter(lambda x: x[0] == x[1], zip(a, a[1:]))))
{1, 2, 5}
你可以用这段代码轻松检查你的机器有多快,有一百万潜在的重复:
首先生成数据
import random
from itertools import chain
a = list(chain(*[[n] * random.randint(1, 2) for n in range(1000000)]))
并运行测试:
set(map(lambda x: x[0], filter(lambda x: x[0] == x[1], zip(a, a[1:]))))
不用说,这个解决方案只在列表已经排序的情况下才有效。
使用sort()函数。重复项可以通过遍历它并检查l1[i] == l1[i+1]来识别。
在没有任何python数据结构的帮助下,你可以简单地尝试下面的代码。这将工作于寻找重复的各种输入,如字符串,列表等。
# finding duplicates in unsorted an array
def duplicates(numbers):
store=[]
checked=[]
for i in range(len(numbers)):
counter =1
for j in range(i+1,len(numbers)):
if numbers[i] not in checked and numbers[j]==numbers[i] :
counter +=1
if counter > 1 :
store.append(numbers[i])
checked.append(numbers[i])
return store
print(duplicates([1,2,2,3,3,3,4,4,5])) # output: [2, 3, 4]
print(duplicates("madam")) # output: ['m', 'a']
使用Set函数 如:-
arr=[1,4,2,5,2,3,4,1,4,5,2,3]
arr2=list(set(arr))
print(arr2)
输出:- [1,2,3,4,5]
使用array删除副本
eg:-
arr=[1,4,2,5,2,3,4,1,4,5,2,3]
arr3=[]
for i in arr:
if(i not in arr3):
arr3.append(i)
print(arr3)
输出: [1,4,2,5,3]
使用Lambda函数
eg:-
rem_duplicate_func=lambda arr:set(arr)
print(rem_duplicate_func(arr))
输出: {1,2,3,4,5}
从字典中删除重复值
eg:-
dict1={
'car':["Ford","Toyota","Ford","Toyota"],
'brand':["Mustang","Ranz","Mustang","Ranz"] } dict2={} for key,value in dict1.items():
dict2[key]=set(value) print(dict2)
输出: {“车”:{“丰田”、“福特”},“品牌”:{“主攻”、“野马”}}
对称差异-删除重复元素
eg:-
set1={1,2,4,5}
set2={2,1,5,7}
rem_dup_ele=set1.symmetric_difference(set2)
print(rem_dup_ele)
输出: {4 7}
推荐文章
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节
- 不区分大小写列表搜索
- TypeError: ` NoneType `对象在Python中不可迭代
- 如何在Vim注释掉一个Python代码块
- python标准库中的装饰符(特别是@deprecated)
- 如何从外部访问本地Django web服务器
- 删除字符串的最后3个字符
- 在python中执行no-op的标准方法是什么?
- 如何从生成器构建numpy数组?
- 什么时候我应该(不)想要在我的代码中使用熊猫apply() ?
- 数据类vs类型。NamedTuple主要用例