filter()

Содержание
Введение
Пример
Применение совместо со split()
Похожие статьи

Введение

# -> returns only those elements of iterable # where function returned True

Синтаксис

filter(function, sequence)

Пример

Простейший пример

# filter() positives = filter(lambda x: x > 0, [1, -5, 0, 6, -2, 8]) print(positives) print(list(positives)) # Filtering with None trues = filter(None, [0, 1, False, True, [], [1, 2, 3], '', 'hello']) print(list(trues)) # In Python2 map() and filter() are not lazy as in Python3. # They are eager and return lists

<filter object at 0x7f5e0bf2e2b0> [1, 6, 8] [1, True, [1, 2, 3], 'hello']

Применение совместо со split()

split() может выдать не совсем тот результат, который вы хотите. В частности он добавляет пустые строки, избавится от которых можно с помощью filter() так как пустая строка возвращает False.

Допустим, нужно из /hei/hei/ получить список из hei и hei

>>> '/hei/hei/'.split('/') ['', 'hei', 'hei', ''] >>> list(filter(None, '/hei/hei/'.split('/'))) ['hei', 'hei']

Article author: Andrei Olegovich

Похожие статьи
Python
*args **kwargs
sys.argv: аргументы командной строки
Лямбда функции
Функции первого класса
Замыкания
Декораторы
Кэширование
if, elif, else
Циклы
Методы
Итерация
Генераторы
Генераторы: Maintaining State
Встроенные фукнции: all() … zip()

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, info@aredel.com 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: