python多个list组成的list去重 考虑顺序

在Python中,如果你有多个列表组成的列表,并且你想要去除其中的重复元素,同时考虑顺序,你可以使用functools.total_ordering装饰器来简化代码,并使用set来去重。

下面是一个示例代码:

c 复制代码
from functools import total_ordering
 
@total_ordering
class ListElement:
    def __init__(self, index, value):
        self.index = index
        self.value = value
    
    def __eq__(self, other):
        return self.value == other.value and self.index == other.index
    
    def __lt__(self, other):
        return self.index < other.index if self.value == other.value else self.value < other.value
 
# 假设lists是一个包含多个列表的列表
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 4, 6]]
 
# 将所有列表的元素转换为ListElement对象
flattened_lists = [ListElement(i, x) for i, sublist in enumerate(lists) for x in sublist]
 
# 使用set去重
unique_elements = list(set(flattened_lists))
 
# 提取去重后元素的值,恢复为列表的列表形式
unique_lists = [[elem.value for elem in grp] for _, grp in groupby(unique_elements, key=lambda x: x.index)]
 
print(unique_lists)

这段代码首先定义了一个ListElement类,它记录了元素的索引和值。这个类实现了__eq__和__lt__方法,以便能够比较元素的顺序。然后,它将所有列表的元素转换为ListElement对象,并使用set去除重复项。最后,它将set中的元素分组回原来的列表形式。

相关推荐
geovindu22 分钟前
go: Visitor Pattern
开发语言·设计模式·golang·访问者模式
宣宣猪的小花园.24 分钟前
C语言重难点全解析:内存管理到位运算
c语言·开发语言·单片机
方安乐4 小时前
python之向量、向量和、向量点积
开发语言·python·numpy
zh1570236 小时前
JavaScript中WorkerThreads解决服务端计算瓶颈
jvm·数据库·python
小小小米粒6 小时前
Collection单列集合、Map(Key - Value)双列集合,多继承实现。
java·开发语言·windows
蜡台6 小时前
Python包管理工具pip完全指南-----2
linux·windows·python
Mr.朱鹏7 小时前
【Python 进阶 | 第四篇】Psycopg3 + Flask 实现 PostgreSQL CRUD 全流程:从连接池到RESTful接口
python·postgresql·flask·virtualenv·fastapi·pip·tornado
czhc11400756637 小时前
C# 428 线程、异步
开发语言·c#
2401_871492857 小时前
Vue.js监听器watch利用回调函数处理级联下拉框数据联动
jvm·数据库·python
FreakStudio7 小时前
亲测可用!可本地部署的 MicroPython 开源仿真器
python·单片机·嵌入式·面向对象·并行计算·电子diy·电子计算机