sorted()

Содержание
Введение
Синтаксис
Пример
sorted + lambda
Похожие статьи

Введение

Синтаксис

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

Пример

python >>> sorted([5, 2, 3, 1, 4])

[1, 2, 3, 4, 5]

>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})

[1, 2, 3, 4, 5]

>>> sorted("This is a test string from Andrei".split(), key=str.lower)

['a', 'Andrei', 'from', 'is', 'string', 'test', 'This']

class Student: def __init__(self, name, grade, age): self.name = name self.grade = grade self.age = age def __repr__(self): return repr((self.name, self.grade, self.age)) student_objects = [ Student('john', 'A', 15), Student('jane', 'B', 12), Student('dave', 'B', 10), ] print(sorted(student_objects, key=lambda student: student.age))

python student_search.py

[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Banner image

Пример применения лямбды для создания ключа при сортировке.

scientists = ['Marie Curie', 'Dmitri Mendeleev', 'Nikolay Basov', 'Alexander Popov', 'Igor Kurchatov', 'Niels Bohr', 'Oliver Heaviside','Max Planck', 'Isaac Newton', 'Rosalind Franklin'] print(sorted(scientists, key=lambda name: name.split()[-1]))

['Nikolay Basov', 'Niels Bohr', 'Marie Curie', 'Rosalind Franklin', 'Oliver Heaviside', 'Igor Kurchatov', 'Dmitri Mendeleev', 'Isaac Newton', 'Max Planck', 'Alexander Popov']

Article author: Andrei Olegovich

Похожие статьи
Функции
Python
Лямбда функции
map()
Banner image

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: