1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| words = ["apple", "banana", "pear", "cherry"] sorted_words = sorted(words, key=len)
data = ['a5', 'a2', 'b1', 'b3', 'c2'] sorted_data = sorted(data, key=lambda x: (x[0], int(x[1:])))
tuples = [(1, 'c'), (2, 'a'), (1, 'b')] sorted_tuples = sorted(tuples, key=lambda x: x[1])
grades = {"Alice": 85, "Bob": 92, "Charlie": 88, "David": 76} sorted_grades = sorted(grades.items(), key=lambda x: x[1])
words = ["banana", "Apple", "cherry", "apple"] sorted_words = sorted(words, key=lambda x: x.lower())
students = [("Alice", 85), ("Bob", 92), ("Charlie", 85), ("David", 76)] sorted_students = sorted(students, key=lambda x: (-x[1], x[0]))
import functools
def compare(x, y): if x[1] < y[1]: return -1 elif x[1] > y[1]: return 1 else: return 0
students = [("Alice", 85), ("Bob", 92), ("Charlie", 85), ("David", 76)] sorted_students = sorted(students, key=functools.cmp_to_key(compare))
|