filter()

Contents
Введение
Пример
Применение совместо со 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']

Related Articles
*args **kwargs
Лямбда функции
all()
any()
map()
zip()
sorted()
Функции первого класса
Замыкания
Декораторы
Кэширование
Python
if, elif, else
Циклы
Методы
enum

Search on this site

Subscribe to @aofeed channel for updates

Visit Channel

@aofeed

Feedbak and Questions in Telegram

@aofeedchat