Created
January 10, 2020 02:54
-
-
Save MetroWind/b180104292b2c69c92bcb9f66a58ba06 to your computer and use it in GitHub Desktop.
A function that returns a function that sorts according to a list of keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def props_to_sort_lambda(*props): | |
"""Return a function that sorts according to property list `props`. | |
The sort is supposed to apply on a list of dictionaries with the same set of | |
keys. Argument `props` is a list of keys for the dicts. | |
Example: | |
xs = [{"aaa": 1, "bbb": 2, ...}, {"aaa": 2, "bbb": 3, ...}, ...] | |
sorted_xs = props_to_sort_lambda("-aaa", "bbb")(xs) | |
This sorts `xs` first by "bbb", and then by "aaa" but reversed. In another | |
word, the result would contain the largest aaa in the beginning, and if two | |
dicts have the same aaa, the one that has the smaller bbb comes first. | |
""" | |
if len(props) == 0: | |
return lambda x:x | |
prop = props[0] | |
reverse = False | |
if prop[0] == '-': | |
prop = prop[1:] | |
reverse = True | |
return lambda xs: sorted(props_to_sort_lambda(*(props[1:]))(xs), | |
key=lambda x:x[prop], reverse=reverse) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment