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中的元素分组回原来的列表形式。

相关推荐
空空kkk6 分钟前
Java基础——代理
java·开发语言
赵谨言7 分钟前
基于YOLOv5的植物目标检测研究
大数据·开发语言·经验分享·python
野生技术架构师7 分钟前
互联网大厂必备 Java 面试八股文真题解析
java·开发语言·面试
不光头强13 分钟前
IO流知识点
开发语言·python
老约家的可汗14 分钟前
C++篇之类和对象下
java·开发语言·c++
水月wwww15 分钟前
Rust的安装与卸载 | windows
开发语言·windows·rust
SouthRosefinch24 分钟前
一、HTML简介与开发环境
开发语言·前端·html
€81130 分钟前
Java入门级教程27——ActiveMQ的下载与应用
java·开发语言·activemq·点对点文本消息发送·点对点对象消息发送·mysql+redis·序列化对象消息传输
Irissgwe34 分钟前
C&C++内存管理
c语言·开发语言·c++·c++内存管理
老师好,我是刘同学34 分钟前
Python列表用法全解析及实战示例
python