Linux 拨号vps windows公众号手机端

Python列表怎么快速查找重复项

lewis 8年前 (2017-02-01) 阅读数 7 #程序编程
文章标签 python

可以使用集合来快速查找重复项。

方法一:使用for循环和集合来查找重复项

def find_duplicates(lst):
    duplicates = set()
    for item in lst:
        if lst.count(item) > 1:
            duplicates.add(item)
    return duplicates

lst = [1, 2, 3, 4, 4, 5, 6, 6, 7]
print(find_duplicates(lst))

输出:

{4, 6}

方法二:使用列表推导式和集合来查找重复项

def find_duplicates(lst):
    return set([item for item in lst if lst.count(item) > 1])

lst = [1, 2, 3, 4, 4, 5, 6, 6, 7]
print(find_duplicates(lst))

输出:

{4, 6}
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门