使用带有 cmp_to_key 的自定义排序逻辑函数对 python 中的对象列表进行排序
Sort list of objects in python using custom sort logic function with cmp_to_key
我在 python 中有一个对象列表,其中单个对象有 2 个属性,即。 a
和 b
,a
可以是 None
或 dict
,b 是 int
或 None
,我想要结果列表排序如下:
- 它应该首先具有
a equal to None
的所有对象。
- 那么它应该有所有带有
a not equal to None
的对象。
- 在1、2中如果那些对象有
b
(b is int
)则用b. 排序
示例结果:
[
Obj(a=None, b=2),
Obj(a=None, b=5),
Obj(a=None, b=None),
Obj(a=dict, b=1),
Obj(a=dict, b=4),
Obj(a=dict, b=None)
]
这将使用 sorted()
来完成,类似的方法适用于 list
数据类型的 sort()
方法:
class Obj:
def __init__(self, a, b):
self.a = a
self.b = b
input = [
Obj(a=dict(), b=1),
Obj(a=dict(), b=None),
Obj(a=None, b=5),
Obj(a=None, b=None),
Obj(a=dict(), b=4),
Obj(a=None, b=2),
]
output = sorted(input, key=lambda x: (x.a is not None, x.b is None, x.b))
[print(f"Obj(a={'dict' if x.a is not None else 'None'}, b={x.b})") for x in output]
输出:
Obj(a=None, b=2)
Obj(a=None, b=5)
Obj(a=None, b=None)
Obj(a=dict, b=1)
Obj(a=dict, b=4)
Obj(a=dict, b=None)
我在 python 中有一个对象列表,其中单个对象有 2 个属性,即。 a
和 b
,a
可以是 None
或 dict
,b 是 int
或 None
,我想要结果列表排序如下:
- 它应该首先具有
a equal to None
的所有对象。 - 那么它应该有所有带有
a not equal to None
的对象。 - 在1、2中如果那些对象有
b
(b is int
)则用b. 排序
示例结果:
[
Obj(a=None, b=2),
Obj(a=None, b=5),
Obj(a=None, b=None),
Obj(a=dict, b=1),
Obj(a=dict, b=4),
Obj(a=dict, b=None)
]
这将使用 sorted()
来完成,类似的方法适用于 list
数据类型的 sort()
方法:
class Obj:
def __init__(self, a, b):
self.a = a
self.b = b
input = [
Obj(a=dict(), b=1),
Obj(a=dict(), b=None),
Obj(a=None, b=5),
Obj(a=None, b=None),
Obj(a=dict(), b=4),
Obj(a=None, b=2),
]
output = sorted(input, key=lambda x: (x.a is not None, x.b is None, x.b))
[print(f"Obj(a={'dict' if x.a is not None else 'None'}, b={x.b})") for x in output]
输出:
Obj(a=None, b=2)
Obj(a=None, b=5)
Obj(a=None, b=None)
Obj(a=dict, b=1)
Obj(a=dict, b=4)
Obj(a=dict, b=None)