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}
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:虚拟主机怎么设置默认首页 下一篇:docker怎么映射宿主机目录
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。