Reputation: 21
I currently have a list of tuples representing edges in a directed graph, of the form (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.
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.
Upvotes: 0
Views: 60
Reputation: 21
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)).
Upvotes: 2