检查 python 列表中的重复项 [英] check for duplicates in a python list

查看:39
本文介绍了检查 python 列表中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到这个问题的很多变体,从简单的删除重复项到查找和列出重复项.即使尝试取这些例子的点点滴滴也没有得到我的结果.

I've seen a lot of variations of this question from things as simple as remove duplicates to finding and listing duplicates. Even trying to take bits and pieces of these examples does not get me my result.

我的问题是如何检查我的列表是否有重复条目?更好的是,我的列表是否有非零重复项?

My question is how am I able to check if my list has a duplicate entry? Even better, does my list have a non-zero duplicate?

我有一些想法 -

#empty list
myList = [None] * 9 

#all the elements in this list are None

#fill part of the list with some values
myList[0] = 1
myList[3] = 2
myList[4] = 2
myList[5] = 4
myList[7] = 3

#coming from C, I attempt to use a nested for loop
j = 0
k = 0
for j in range(len(myList)):
    for k in range(len(myList)):
        if myList[j] == myList[k]:
            print "found a duplicate!"
            return

如果这行得通,它会在列表中找到重复项(无).有没有办法忽略 None 或 0 的情况?我不在乎两个元素是否为 0.

If this worked, it would find the duplicate (None) in the list. Is there a way to ignore the None or 0 case? I do not care if two elements are 0.

我想到的另一个解决方案是将列表转换为集合并比较集合和列表的长度以确定是否存在重复项,但是在运行 set(myList) 时,它不仅会删除重复项,还会对其进行排序.我可以有单独的副本,但似乎是多余的.

Another solution I thought of was turn the list into a set and compare the lengths of the set and list to determine if there is a duplicate but when running set(myList) it not only removes duplicates, it orders it as well. I could have separate copies, but it seems redundant.

推荐答案

如果您只是想检查它是否包含重复项.一旦该函数找到出现多次的元素,它就会作为重复项返回.

If you simply want to check if it contains duplicates. Once the function finds an element that occurs more than once, it returns as a duplicate.

my_list = [1, 2, 2, 3, 4]

def check_list(arg):
    for i in arg:
        if arg.count(i) > 1:
            return 'Duplicate'

print check_list(my_list) == 'Duplicate' # prints True

这篇关于检查 python 列表中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆