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

相关推荐
用户956256254293 小时前
跟做:Firecrawl 单页转 Markdown 再丢进沙箱总结
python·api
威哥爱编程3 小时前
模拟面试智能体开发实战 02:回答等半分钟,谁还愿意练?把服务端和流式输出搭起来
python·agent·harmonyos
威哥爱编程3 小时前
模拟面试智能体开发实战 01:面试挂了都不知道挂在哪?用 Python 给自己造一个随叫随到的 AI 面试官
python·agent·harmonyos
2601_967980113 小时前
Python行情API量化 02:顺序拉 20 要 2 秒?并发批量把时间压到 0.5 秒
python·api·限流·并发·量化
伞伞悦读3 小时前
【第81期】特征缩放怎么选:标准化、MinMax 与 Robust 的原理、泄漏对照和完整实验
人工智能·python·深度学习·机器学习
新*4 小时前
从一段 WebSocket 代码聊开:bytes 不是 zlib、binaryType 决定一切,15MB 大消息的零拷贝优化
javascript·python·websocket·性能优化·blob·zlib·arraybuffer
David猪大卫5 小时前
【C++修炼】map 和 set 的使用
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
卷无止境6 小时前
mathmodel-figure-templates 以及两个上手案例
后端·python
fengci.6 小时前
CTF2MISC中等部分
开发语言·前端·学习
锋行天下7 小时前
服务器 Python 2.7 装不了 langgraph-cli?用本地生成 Dockerfile 曲线救国
人工智能·后端·python