简体   繁体   中英

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). 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.

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)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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