Python Glossary Русский

all Python 3Functionsterm

sorted() with key=

functional

Returns a new sorted list. key= sets the function that produces the sort key. reverse= gives the reverse order.

Syntax

sorted(iterable, key=None, reverse=False)

The sort is stable: items with equal keys keep their original order, so multi-level sorts are done in several passes starting from the least significant key. The key function is called exactly once per element, not on every comparison, so an expensive key is cheap; unlike list.sort(), sorted() leaves the original untouched and accepts any iterable.

Examples

words = ['banana', 'apple', 'cherry', 'kiwi']
print(sorted(words))  # → алфавит
print(sorted(words, key=len))  # → по длине
print(sorted(words, key=len, reverse=True))  # → ['banana', 'cherry', 'apple', 'kiwi']
# key=str.lower — регистронезависимо
mixed = ['Banana', 'apple', 'Cherry']
print(sorted(mixed, key=str.lower))  # → ['apple', 'Banana', 'Cherry']
# Сортировка кортежей
pairs = [(2,'b'),(1,'a'),(3,'c')]
print(sorted(pairs))  # → [(1,'a'),(2,'b'),(3,'c')]
print(sorted(pairs, key=lambda p: p[1]))  # → по буквам
# Словари по значению
d = {'a':3,'b':1,'c':2}
print(sorted(d, key=d.get))  # → ['b','c','a']
# Вторичный ключ: по убыванию оценки, при равенстве — по имени
students = [('Alice', 85), ('Bob', 90), ('Carol', 85)]
print(sorted(students, key=lambda s: (-s[1], s[0])))  # → [('Bob', 90), ('Alice', 85), ('Carol', 85)]
nums = [3, -1, 4, -1, 5, -9]
print(sorted(nums, key=abs))  # → [-1, -1, 3, 4, 5, -9]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy