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

相关推荐
mit6.82410 分钟前
[Nagios Core] struct监控对象 | 配置.cfg加载为内存模型
c语言·开发语言
Kyln.Wu25 分钟前
【python实用小脚本-139】Python 在线图片批量下载器:requests+PIL 一键保存网络图像
数据库·python·php
序属秋秋秋28 分钟前
《C++初阶之STL》【泛型编程 + STL简介】
开发语言·c++·笔记·学习
NCHUtianlin30 分钟前
JAVA生成PDF(itextpdf)
java·开发语言·pdf
Sylvia-girl6 小时前
Java——抽象类
java·开发语言
Yana.nice8 小时前
Bash函数详解
开发语言·chrome·bash
江沉晚呤时9 小时前
在 C# 中调用 Python 脚本:实现跨语言功能集成
python·microsoft·c#·.net·.netcore·.net core
电脑能手10 小时前
如何远程访问在WSL运行的Jupyter Notebook
ide·python·jupyter
tomorrow.hello10 小时前
Java并发测试工具
java·开发语言·测试工具
Edward-tan10 小时前
CCPD 车牌数据集提取标注,并转为标准 YOLO 格式
python