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

相关推荐
AC赳赳老秦17 分钟前
文旅市场公开数据分析:基于 OpenClaw 采集景区客流与门票公示数据,生成区域文旅热度监测报告
java·c语言·python·php·symfony·deepseek·openclaw
青 春 记 忆18 分钟前
零基础入门python68:FastAPI 完整博客运行与项目验收
python·fastapi·后端开发
鹿鹿学长21 分钟前
发题前三天,组委会在过三道关:赛题七渠道首发、知网统一收卷、AI 详情 PDF 首进支撑材料
python·自动化
云小逸24 分钟前
C++ 第一阶段:对象、内存与生命周期
开发语言·c++
玖玥拾39 分钟前
Lua 基础语法(二)
开发语言·unity·lua
王的宝库43 分钟前
GO常用标准库包
开发语言·后端·golang
geovindu1 小时前
python: Face Recognition
开发语言·后端·python·人脸识别
平头哥技术团队1 小时前
Day 13 | 调 line-height 和 margin:三处间距让名片页脱离模板感
开发语言·前端·javascript·学习·html5
2601_954811821 小时前
AI科学实验室MHS标准解读:AI智能体如何统一控制实验室设备接口
人工智能·python
一位正在转型AI全栈的前端工程师1 小时前
AI 全栈学习之旅 -Week 9:什么是AI Agent?从Function Calling到LangGraph
前端·python