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

相关推荐
用户8356290780511 分钟前
从一维到二维:用Spire.XLS轻松将Python列表导出到Excel
后端·python
破刺不会编程5 分钟前
socket编程TCP
linux·运维·服务器·开发语言·网络·网络协议·tcp/ip
北极糊的狐7 分钟前
IDEA中安装 CamelCase 插件实现变量快速生成驼峰命名
开发语言·php
【蜡笔小新】14 分钟前
《筑基篇》C语言基础2
c语言·开发语言
l木本I31 分钟前
uv 技术详解
人工智能·python·深度学习·机器学习·uv
洛阳泰山42 分钟前
Java实现周易六爻自动排盘:根据起卦的公历时间换算农和干支时间,推算日柱空亡(旬空)
java·开发语言·周易·六爻·算卦
宁大小白1 小时前
pythonstudy Day31
python·机器学习
Smile丶凉轩1 小时前
C++ 高性能内存池面试题总结
开发语言·c++
江上鹤.1481 小时前
Day34模块和库的导入
python
我爱鸢尾花1 小时前
第十四章聚类方法理论及Python实现
大数据·python·机器学习·数据挖掘·数据分析·聚类