【Python】列表去重方法

版权声明:欢迎交流,转载请注明出处。 https://blog.csdn.net/u013034226/article/details/85010079

如题:python中列表去重,使用三种基础方法。

使用集合

  • 集合中的元素是唯一的,所以利用集合进行去重
list1 = [2, 3, 56, 5, 5, 3 ]

def func1(list1):  
	    ''''' 使用集合 '''  
	    return list(set(list1))

使用列表推导式

def func2(list1):  
	    ''''' 使用列表推导的方式 '''  
	    temp_list=[]  
	    for one in list1:  
	        if one not in temp_list:  
	            temp_list.append(one)  
	    return temp_list  

利用字典key的唯一性

  • 字典的key是唯一的,利用{}的fromkeys方法进行去重
  • 源码中的fromkeys方法
    def fromkeys(*args, **kwargs): # real signature unknown
        """ Returns a new dict with keys from iterable and values equal to value. """
        pass
  • 具体实现方法:
def func3(list1):  
	    ''''' 使用字典的方式 '''  
	    return {}.fromkeys(list1).keys() 
print(func2(list1))
print(type(func2(list1)))
# 去重结果:dict_keys([2, 3, 56, 5])
# 类型:<class 'dict_keys'>

猜你喜欢

转载自blog.csdn.net/u013034226/article/details/85010079
今日推荐