tg-me.com/pyproglib/6602
Last Update:
В Python break
в циклах for
прерывает итерацию, но часто есть более читаемые и лаконичные способы. Разберём типичные случаи и их альтернативы.
Классика с break
:
color_options = ["blue", "green", "purple"]
is_purple_an_option = False
for color in color_options:
if color == "purple":
is_purple_an_option = True
break
Альтернатива — оператор
in
:is_purple_an_option = "purple" in color_options
in
работает со всеми итерируемыми объектами, а для set
и dict
ещё и быстрее, чем цикл.Пример с
break
:points_per_user = [3, 12, 28, 105]
anyone_has_100 = False
for points in points_per_user:
if points > 100:
anyone_has_100 = True
break
Альтернатива —
any
:anyone_has_100 = any(points > 100 for points in points_per_user)
any
(или all
для "все элементы") делает код выразительнее.С
break
:words = ["Look", "at", "these", "excellent", "words"]
first_long_word = None
for word in words:
if len(word) > 4:
first_long_word = word
break
Альтернатива —
next
с генератором:long_words = (word for word in words if len(word) > 4)
first_long_word = next(long_words, None)
next
берёт первый элемент из генератора, а None
— значение по умолчанию, если ничего не найдено.С
break
:items = ["chair", "desk", "", "lamp"]
before_blank = []
for item in items:
if not item:
break
before_blank.append(item)
Альтернатива —
itertools.takewhile
:from itertools import takewhile
before_blank = list(takewhile(bool, items))
takewhile
собирает элементы, пока условие истинно, и возвращает итератор.break
полезен, но часто его можно заменить:—
in
— для проверки наличия—
any/all
— для условий—
next
— для поиска первого значения—
takewhile
— для сбора до условияbreak
?Библиотека питониста #буст