python - 如何对 Python 对象进行排序

标签 python list python-3.x nested-lists

我有一个嵌套列表,其中包含不同的对象,它们是嵌套列表中重复的对象对,我试图删除它们,但我一直得到一个

TypeError: unorderable types: practice() < practice()

我知道这个错误是由于我尝试使用对象而不是整数引起的,但我不知道如何删除重复项,这是我尝试过的

class practice:
    id = None

    def __init__(self,id):
        self.id = id

a = practice('a')
b = practice('b')
c = practice('c')
d = practice('d')
e = practice('e')
f = practice('f')

x = [[a,b],[c,d],[a,b],[e,f],[a,b]]

unique_list = list()
for item in x:
    if sorted(item) not in unique_list:
        unique_list.append(sorted(item))

print(unique_list)

最佳答案

如果你想通过id比较对象:

class practice:
    id = None

    def __init__(self,id):
        self.id = id

    def __lt__(self, other):
        return other.id > self.id

    def __gt__(self, other):
        return self.id > other.id

unique_list = list()
for item in x:
    if sorted(item) not in unique_list:
        unique_list.append(sorted(item))

print(unique_list)
[[<__main__.practice object at 0x7fe87e717c88>, <__main__.practice object at 0x7fe87e717cc0>],
 [<__main__.practice object at 0x7fe86f5f79e8>, <__main__.practice object at 0x7fe86f589278>],
 [<__main__.practice object at 0x7fe86f589be0>, <__main__.practice object at 0x7fe86f589c18>]]

根据您要实现的所有功能,rich comparison ordering methods你可以使用 functools.total_ordering ,您只需要定义其中一种方法,它会处理其余的事情

from functools import total_ordering
@total_ordering
class practice:
    id = None

    def __init__(self,id):
        self.id = id

    def __lt__(self, other):
        return other.id > self.id

    def __eq__(self, other):
        return self.id == other.id

Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest. This simplifies the effort involved in specifying all of the possible rich comparison operations:

The class must define one of __lt__(), __le__(), __gt__(), or __ge__(). In addition, the class should supply an __eq__() method.

关于python - 如何对 Python 对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29811547/

相关文章:

list - 如何在 Ansible 中连接两个字典列表

python-3.x - 我想将国家列表与列数据进行比较,列数据是 pandas 数据框 Python 中的字典对象类型

python - 识别列表列表中的重复项并总结他们的最后一项

python - 透明地将值分配给自定义数字类型

python - 使用元素树读取 xml 文件

python - 在 Spotfire 中加载数据表后执行 IronPython 脚本

python-3.x - 单词不在词汇表中

python - 如何使用python3提取样本前面的文字?

python - matplotlib 的 griddata 的奇怪行为

python - 用于解析 Python 源以在全局变量后提取文档字符串的示例 ast 代码