python 列表去重(不可变类型和可变类型)
来源:互联网 发布:表达知错的句子 编辑:程序博客网 时间:2024/06/04 19:42
不可变类型
- 利用set特性去重
ids = [1, 3, 8, 3, 8, 1, 9, 9, 9, 1]ids = list(set(ids))
- 新建一个list,循环遍历
ids = [1, 3, 8, 3, 8, 1, 9, 9, 9, 1]new_ids = []for item in ids: if item not in new_ids: new_ids.append(item)
- 使用reduce处理
ids = [1, 3, 8, 3, 8, 1, 9, 9, 9, 1]func = lambda x, y: x if y in x else x + [y]ids = reduce(func, [[], ] + ids)
可变类型
- 用set处理
class A: def __init__(self, no, name): self.no = no self.name = name def __eq__(self, other): return self.no == other.no and self.name == other.name def __hash__(self): return hash(self.no) ^ hash(self.name) def __repr__(self): return str(self.no)+":"+self.namea_list = [A(1, "a"), A(2, "a"), A(1, "a"), A(1, "b")]a_list = list(set(a_list))# a_list = [1:b, 2:a, 1:a]a_list.sort(key=lambda a: a.no) # 按no排序a_list.sort(key=lambda a: a.name) # 按name排序
必须实现”__eq__”和”__hash__”方法。
“__eq__”用于判断是否相等,”__hash__”用于计算hash值。
因为set存取的必须是不可变类型,它是依赖”__hash__”来计算桶的位置,而利用”__eq__”来判断元素之间是否相等。
关于其更多的介绍:https://segmentfault.com/a/1190000003969462
- 新建一个list,循环遍历
class A: def __init__(self, no, name): self.no = no self.name = name def __eq__(self, other): return self.no == other.no and self.name == other.name def __repr__(self): return str(self.no)+":"+self.namea_list = [A(1, "a"), A(2, "a"), A(1, "a"), A(1, "b")]new_a_list = []for a in a_list: if a not in new_a_list: new_a_list.append(a)
注意这里实现了”__eq__”方法,才能使得“if a not in new_a_list:”语句生效。
- 使用字典dict记录
如果不想实现”__eq__”方法,且元素存在”主键”属性(根据其区分对象相等不相等),则可以使用字典dict来记录列表元素出现与否(置0或1),然后遇到非0的就删除该元素即可。
class A: def __init__(self, no, name): self.no = no self.name = name def __repr__(self): return str(self.no)+":"+self.name# no为"主键"a_list = [A(1, "a"), A(2, "b"), A(1, "a"), A(3, "b")]mp = {}for a in a_list: if a.no not in mp: mp[a.no] = 1 else: mp[a.no] += 1 a_list.remove(a)
阅读全文
0 0
- python 列表去重(不可变类型和可变类型)
- python 可变不可变类型
- python的可变类型和不可变类型
- Python 引用 :可变类型和不可变类型
- python可变类型与不可变类型
- 可变类型和不可变类型
- python 可变 与 不可变类型
- python中的可变与不可变类型
- Python函数之可变类型与不可变类型
- Python的可变类型与不可变类型
- Python的可变类型与不可变类型
- python类的可变类型成员和不可变类型成员的区别
- java中可变类型和不可变类型
- Java中可变类型和不可变类型
- Python探索记(16)——Python的可变类型与不可变类型
- Python学习笔记——可变类型&不可变类型&深拷贝&浅拷贝
- 2.1.7可变类型与不可变类型
- python可变对象和不可变对象
- Sensing Pressure Distribution on a Lower-Limb Exoskeleton
- Android中Fragment的使用
- C# 面向过程 猜拳游戏
- js 开发遇到的问题
- Kotlin学习(一)简单了解下Kotlin
- python 列表去重(不可变类型和可变类型)
- 在centos7.x系统,配置docker私有镜像仓库
- 定时任务-spring-quartz
- Effective Java读书笔记二一(Java Tips.Day.21)
- 搞了一天,为了一个防火墙的没有禁止成功!!!redhat 7 & Oracle Linux 7 & Centos 7注意!!
- es6中的class类下
- 在centos下,关于docker环境变量文件的问题
- SVN trunk(主线) branch(分支) tag(标记) 用法详解和详细操作步骤
- MongoDB C100DEV 2.CRUD