Python 按字典顺序对元组进行排序:
首先比较前两项,如果它们不同,则确定比较的结果;如果它们相等,则比较接下来的两项,依此类推,直到任一序列用完。
举个例子,
In [33]: import heapq
In [34]: A = [(1,100,2)]
In [35]: B = [(2,0,0)]
In [40]: list(heapq.merge(A,B))
Out[40]: [(1, 100, 2), (2, 0, 0)]
In [41]: (1, 100, 2) < (2, 0, 0)
Out[41]: True
因此,不一定正确
a >= x and b >= y and c >= z
可以heapq
在任何可排序对象集合上使用,包括自定义类的实例。使用自定义类,您可以安排任何您喜欢的排序规则。例如,
class MyTuple(tuple):
def __lt__(self, other):
return all(a < b for a, b in zip(self, other))
def __eq__(self, other):
return (len(self) == len(other)
and all(a == b for a, b in zip(self, other)))
def __gt__(self, other):
return not (self < other or self == other)
def __le__(self, other):
return self < other or self == other
def __ge__(self, other):
return not self < other
A = [MyTuple((1,100,2))]
B = [MyTuple((2,0,0))]
print(list(heapq.merge(A,B)))
# [(2, 0, 0), (1, 100, 2)]
但是请注意,尽管这改变了我们对<
for的概念MyTuple
,但不能保证返回的结果heapq.merge
满足
a <= x and b <= y and c <= z
为此,我们必须首先删除所有相互不可排序的项目A
。B