简体   繁体   English

Python:对元组列表进行排序,其中元组包含对象和整数

[英]Python: Sorting a list of tuples, where the tuples contain objects and ints

I currently have a list of tuples representing edges in a directed graph, of the form (startVertex, endVertex, edgeWeight). 我目前有一个元组列表,表示有向图中的边,形式为(startVertex,endVertex,edgeWeight)。 I want to sort this list by edge weight, and in the cases of a tie, by lexicographic order of the vertex self.value string, and then finally by the endVertex self.value in the case of a tie between the startVertex value strings. 我想按边缘权重对此列表进行排序,在平局的情况下,按顶点self.value字符串的字典顺序排序,然后在startVertex值字符串之间的关系中,最后按endVertex self.value排序。

I have searched a fair amount for a solution, but I can't seem to find one. 我已经搜索了很多解决方案,但是似乎找不到。 I can sort by just weight with a sorted(list, key=itemgetter(2)) or by just by vertex value using lambda functions, but I can't find a way to do both at the same time. 我可以仅通过权重使用sorted(list,key = itemgetter(2))进行排序,也可以仅通过使用lambda函数的顶点值进行排序,但是我找不到同时实现两者的方法。

There turns out to be a pretty easy solution actually. 事实证明,这实际上是一个非常简单的解决方案。 I simply added a method to my vertex class: 我只是在顶点类中添加了一个方法:

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

and sorting with 和排序

sorted(edgeList, key = itemgetter(2, 0, 1), reverse = True)

provided the behavior I wanted ( where the tuple was defined by (start vertex, end vertex, edge weight)). 提供了我想要的行为(元组的定义是((起始顶点,终止顶点,边权重))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM