重复列表内部

时间:2015-02-23 16:23:58

标签: python python-3.x

如果列表中的任何两个项目相同,我想构建一个返回True的函数。

例如,[1,7,3,7,4]应该返回True["one","ONE","One"]应该返回False

我需要帮助python的哪些部分寻找重复项。

3 个答案:

答案 0 :(得分:2)

循环显示值并使用set跟踪您已经看到的内容。只要您再次看到,就返回True

def has_duplicates(lst):
    seen = set()
    for elem in lst:
        if elem in seen:
            return True
        seen.add(elem)
    return False

这非常有效,因为它短路;如果早期检测到重复,它就不会遍历整个列表。

答案 1 :(得分:1)

Martijn的answer是最好的,但除了少数例外,这值得一试。

>>> chk = lambda x: len(l) != len(set(l)) # check the length after removing dupes. 
>>> l = [1,7,3,7,4] 
>>> chk(l)
True
>>> l = ["one","ONE","One"]
>>> chk(l)
False

注意 - 在评论中提及Martijn,这是一个较慢的过程。

答案 2 :(得分:1)

使用collections.Counter词典:

from collections import Counter
def has_dupes(l):
    # if most repeated key count is > 1 we have at least one dupe
    return Counter(l).most_common(1)[0][1] > 1

或使用any

def has_dupes(l):
    return any(v > 1 for v in Counter(l).values())