Skip to main content
 首页 » 编程设计

python:类对象的多维排序

2025年05月04日17wuhuacong

有没有一种方法可以先对列表中的 x、y 和 z 进行排序。我不确定我的代码是否会这样做:(ch 是一个具有属性 left_edge 的对象)

ch.sort(cmp=lambda x,y: cmp(x.left_edge[0], y.left_edge[0])) 
ch.sort(cmp=lambda x,y: cmp(x.left_edge[1], y.left_edge[1])) 
ch.sort(cmp=lambda x,y: cmp(x.left_edge[2], y.left_edge[2])) 

简单的例子:

unsorted 
(1,1,2),(2,1,1),(1,1,3),(2,1,2) 
sorted 
(1,1,2),(1,1,3),(2,1,1),(2,1,2) 

但我需要排序的对象...

请您参考如下方法:

这正是默认 tuple 比较器的工作方式:

>>> l = [(1, 1, 2), (2, 1, 1), (1, 1, 3), (2, 1, 2)] 
>>> sorted(l) 
[(1, 1, 2), (1, 1, 3), (2, 1, 1), (2, 1, 2)] 

参见the documentation中的对比说明:

Comparison of objects of the same type depends on the type:

  • Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

    If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).