pythonsortingone-liner

Sort the people using a single line


I crossed by this question on LeetCode: https://leetcode.com/problems/sort-the-people/description

This is a VERY simple question, where the idea is to sort "a list of people" by their given "heights". After a few seconds I came out with the following code:

# Input: names = ["Mary","John","Emma"], heights = [180,165,170]
# Output: ["Mary","Emma","John"]

def sortPeople(names: List[str], heights: List[int]) -> List[str]:
        d = {heights[i]:names[i] for i in range(len(names))}
        return [d[h] for h in sorted(d.keys(), reverse=True)]

I was wondering if we can use only one line here, without repeating code and/or repeating calculations.


Solution

  • names = ["Mary","John","Emma"]
    heights = [180,165,170]
    
    [names[i] for i in sorted(range(len(names)), key=lambda x: heights[x], reverse=True)]
    
    >>> ['Mary', 'Emma', 'John']