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

相关推荐
Zane199417 分钟前
create_task 和直接 await 到底有什么不一样?asyncio 的 Task、gather 与并发数量控制
后端·python
李可以量化19 分钟前
Redis 从了解到精通(四・下):分区技术原理与选型全解析
python
Python私教31 分钟前
创业团队做管理系统,别先堆页面:我把 14 个问题做成了需求门禁
后端·python·架构
Logintern0938 分钟前
[Matlab] 遗传算法求解TSP入门
开发语言·matlab
云半S一39 分钟前
Python学习总结
python·学习·学习分享
苏子寒42 分钟前
Nano-VLLM全代码解析笔记(6)-embed_head和linear
pytorch·笔记·python·机器学习·ai·nlp·vllm
JTaoX1 小时前
PyCharm 连接本地虚拟机完整指南
ide·python·pycharm
Hi_Amos1 小时前
记一次 yfinance 源码调试:SOCKS5 代理下 Chart API 正常,历史数据却一直超时
python·k线·yfinance
练习时长两年半的RL练习生1 小时前
与AI对话后对 Actor-Critic 中 TD Target 的 a‘ 来源总结
开发语言·人工智能·php
青少儿编程课堂1 小时前
用图形化编程做一个“少年探险闯关”小游戏:方向键控制、碰撞检测与多关卡串起完整项目
c++·python·算法·bfs·信息学竞赛