简体   繁体   中英

How do I Sort a Zipped List of Three Vals where I want first two Reversed (Descending) and Third is not (Ascending)?

I am trying to sort three lists that have been zipped. I would like it sorted in reverse for the first two columns (highest to lowest) and then by the third in ascending (lowest to highest). So in the below example, by highest world ranking first, then by highest score, then by names, with the lexicographically shorter name first.

I can accomplish the first part using the following:

names = ["name1", "McNamealot", "Namey Name Name", "Namey", "afirst"]
scores = [1,3,42,42,5]
world_rankings = [850,750,650,550,450]

zipped = zip(world_rankings, scores, names)

def sorter(item):
    return item[0], item[1] 
            
zipperoni = sorted(zipped, key = sorter, reverse = True)

However, I can't figure out how to get the third column without overwriting the correct sort of the first two.

I'm sure I'm missing some basic concept. Any answer, and ofc explanation, would be greatly appreciated.

Correct Answer:

sorted(zipped, key=lambda item: (-item[0], -item[1], item[2]))

Thanks Mechanic Pig for the super fast response!

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