zoukankan      html  css  js  c++  java
  • 【转】列表去重的几种方法

    转自地址:https://blog.csdn.net/Jerry_1126/article/details/79843751

    方法一: 使用内置set方法来去重

    >>> lst1 = [2, 1, 3, 4, 1]
    >>> lst2 = list(set(lst1))
    >>> print(lst2)
    [1, 2, 3, 4]
    

    方法二: 使用字典中fromkeys()的方法来去重

    >>> lst1 = [2, 1, 3, 4, 1]
    >>> lst2 = {}.fromkeys(lst1).keys()
    >>> print(lst2)
    dict_keys([2, 1, 3, 4])
    

    方法三: 使用常规方法来去重

    >>> lst1 = [2, 1, 3, 4, 1]
    >>> temp = []
    >>> for item in lst1:
    	    if not item in temp:
    		    temp.append(item)	
    >>> print(temp)
    [2, 1, 3, 4]
    

    方法四: 使用列表推导来去重

    >>> lst1 = [2, 1, 3, 4, 1]
    >>> temp = []
    >>> [temp.append(i) for i in lst1 if not i in temp]
    [None, None, None, None]
    >>> print(temp)
    [2, 1, 3, 4]
    

    方法五: 使用sort函数来去重

    >>> lst1 = [2, 1, 3, 4, 1]
    >>> lst2.sort(key=lst1.index)
    >>> print(lst2)
    [2, 1, 3, 4]
    

    方法六: 使用sorted函数来去重

    >>> lst1 = [2, 1, 3, 4, 1]
    >>> lst2 = sorted(set(lst1), key=lst1.index)
    >>> print(lst2)
    [2, 1, 3, 4]
    

    备注: 前面的几种方法,有几种是不能保证其顺序的,比如用set()函数来处理!

    如果要删除列表列表中的重复项,则同样可以用下面的几种方法来处理

    >>> # 方法一:
    >>> data = [2, 1, 3, 4, 1]
    >>> [item for item in data if data.count(item) == 1]
    [2, 3, 4]
    
    >>> # 方法二:
    >>> data = [2, 1, 3, 4, 1]
    >>> list(filter(lambda x:data.count(x) == 1, data))
    [2, 3, 4]
    
  • 相关阅读:
    前缀和
    hdu6290奢侈的旅行
    make_pair
    New Year and Buggy Bot
    STL next_permutation 算法原理和自行实现
    前端面试题集合
    node设置cookie
    黑客与geek
    xss
    node async
  • 原文地址:https://www.cnblogs.com/everfight/p/remove_duplicate_from_list.html
Copyright © 2011-2022 走看看