sorted()

Contents
Введение
Синтаксис
Пример
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)]

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

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']

Related Articles
Функции
Python
Лямбда функции
map()

Search on this site

Subscribe to @aofeed channel for updates

Visit Channel

@aofeed

Feedbak and Questions in Telegram

@aofeedchat