首页 > 编程知识 正文

python中列表怎么去重,python中实现列表去重的方法是

时间:2023-05-04 16:25:26 阅读:274907 作者:3083

如题: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(func3(list1))print(type(func3(list1)))# 去重结果:dict_keys([2, 3, 56, 5])# 类型:<class 'dict_keys'>

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。