This is the sample when sorting with multiple keys in descending order.
cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'Buick', 'year': 2018},
{'car': 'Buick', 'year': 2019},
{'car': 'BMW', 'year': 2019},
{'car': 'Faraday', 'year': 2014},
{'car': 'VW', 'year': 2011},
{'car': 'Lincoln', 'year': 2017},
]
print("cars")
print(*cars, sep="\n")
cars_sorted = sorted(cars, key = lambda x: ([-ord(c) for c in x["car"]], -x["year"]))
print("sorted cars")
print(*cars_sorted, sep="\n")
For string to do reversed order, a little trick is to convert character to ascii code number.
{'car': 'VW', 'year': 2011}
{'car': 'Mitsubishi', 'year': 2000}
{'car': 'Lincoln', 'year': 2017}
{'car': 'Ford', 'year': 2005}
{'car': 'Faraday', 'year': 2014}
{'car': 'Buick', 'year': 2019}
{'car': 'Buick', 'year': 2018}
{'car': 'BMW', 'year': 2019}
No comments:
Post a Comment