我在python中有一個物件串列,其中一個物件有2個屬性,即。aand b,a可以是Noneordict并且 b 是intor 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)
]
uj5u.com熱心網友回復:
這將使用 來完成sorted(),并且類似的方法將適用于資料型別的sort()方法list:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/437124.html
標籤:Python python-3.x 排序
