如何在整数列表中找到重复项并创建重复项的另一个列表?
当前回答
使用sort()函数。重复项可以通过遍历它并检查l1[i] == l1[i+1]来识别。
其他回答
有点晚了,但可能对一些人有帮助。 对于一个比较大的列表,我发现这个方法很适合我。
l=[1,2,3,5,4,1,3,1]
s=set(l)
d=[]
for x in l:
if x in s:
s.remove(x)
else:
d.append(x)
d
[1,3,1]
显示正确和所有重复,并保持秩序。
这里有一个简洁明了的解决方案——
for x in set(li):
li.remove(x)
li = list(set(li))
使用熊猫:
>>> import pandas as pd
>>> a = [1, 2, 1, 3, 3, 3, 0]
>>> pd.Series(a)[pd.Series(a).duplicated()].values
array([1, 3, 3])
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
some_dictionary = {}
for element in some_list:
if element not in some_dictionary:
some_dictionary[element] = 1
else:
some_dictionary[element] += 1
for key, value in some_dictionary.items():
if value > 1:
print(key, end = ' ')
# another way
duplicates = []
for x in some_list:
if some_list.count(x) > 1 and x not in duplicates:
duplicates.append(x)
print()
print(duplicates)
来源:这里
在没有任何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']
推荐文章
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- 在javascript中从平面数组构建树数组
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?