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

相关推荐
站大爷IP4 分钟前
Python自动整理音乐文件:按艺术家和专辑分类歌曲
python
BBB努力学习程序设计5 分钟前
Python 高效处理大数据:生成器(Generator)的工作机制与实战技巧
python
ysdysyn42 分钟前
C# Modbus RTU 多从站控制全攻略:一端口,双轴控制
开发语言·c#·mvvm·通讯·modbus rtu
hashiqimiya1 小时前
java程序的并发
java·开发语言·python
2301_811958381 小时前
浏览器下载huggingface网络连接超时,使用镜像源教程
python·tokenizer
微露清风1 小时前
系统性学习C++进阶-第十四讲-二叉搜索树
开发语言·c++·学习
red润1 小时前
Python环境变量自动配置:实现生产与开发环境无缝切换
后端·python
知识进脑的肖老千啊1 小时前
LangGraph简单讲解示例——State、Node、Edge
人工智能·python·ai·langchain
董世昌411 小时前
强制类型转换和隐式类型转换的区别
开发语言
Fruiticecake1 小时前
Markdown,不用鼠标也能做笔记!
开发语言