Python filter list with list

№31 Функция Filter() / для начинающих

Функция filter() в Python применяет другую функцию к заданному итерируемому объекту (список, строка, словарь и так далее), проверяя, нужно ли сохранить конкретный элемент или нет. Простыми словами, она отфильтровывает то, что не проходит и возвращает все остальное.

Объект фильтра — это итерируемый объект. Он сохраняет те элементы, для которых функция вернула True . Также можно конвертировать его в list, tuple или другие типы последовательностей с помощью фабричных методов.

В этом руководстве разберемся как использовать filter() с разными типами последовательностей. Также рассмотрим примеры, которые внесут ясность в принцип работы.

Функция filter() принимает два параметра. Первый — имя созданной пользователем функции, а второй — итерируемый объект (список, строка, множество, кортеж и так далее).

Она вызывает заданную функцию для каждого элемента объекта как в цикле. Синтаксис следующий:

 
# Синтаксис filter()

filter(in_function|None, iterable)
|__filter object

Первый параметр — функция, содержащая условия для фильтрации входных значений. Она возвращает True или False . Если же передать None , то она удалит все элементы кроме тех, которые вернут True по умолчанию.

Второй параметр — итерируемый объект, то есть последовательность элементов, которые проверяются на соответствие условию. Каждый вызов функции использует один из объектов последовательности для тестирования.

Возвращаемое значение — объект filter , который представляет собой последовательность элементов, прошедших проверку.

Примеры функции filter()

Фильтр нечетных чисел

В этом примере в качестве итерируемого объекта — список числовых значений

Источник

How to Filter List Elements in Python

Summary: in this tutorial, you’ll learn how to filter list elements by using the built-in Python filter() function.

Introduction to Python filter() function

Sometimes, you need to iterate over elements of a list and select some of them based on specified criteria.

Suppose that you have the following list of scores :

scores = [70, 60, 80, 90, 50]Code language: Python (python)

To get all elements from the scores list where each element is greater than or equal to 70, you use the following code:

scores = [70, 60, 80, 90, 50] filtered = [] for score in scores: if score >= 70: filtered.append(score) print(filtered)Code language: Python (python)
  • First, define an empty list ( filtered ) that will hold the elements from the scores list.
  • Second, iterate over the elements of the scores list. If the element is greater than or equal to 70, add it to the filtered list.
  • Third, show the filtered list to the screen.

Python has a built-in function called filter() that allows you to filter a list (or a tuple) in a more beautiful way.

The following shows the syntax of the filter() function:

filter(fn, list)Code language: Python (python)

The filter() function iterates over the elements of the list and applies the fn() function to each element. It returns an iterator for the elements where the fn() returns True .

In fact, you can pass any iterable to the second argument of the filter() function, not just a list.

The following shows how to use the filter() function to return a list of scores where each score is greater than or equal to 70:

scores = [70, 60, 80, 90, 50] filtered = filter(lambda score: score >= 70, scores) print(list(filtered)) Code language: Python (python)
[70, 80, 90]Code language: Python (python)

Since the filter() function returns an iterator, you can use a for loop to iterate over it. Or you can use the list() function to convert the iterator to a list.

Using the Python filter() function to filter a list of tuples example

Suppose you have the following list of tuples:

countries = [ ['China', 1394015977], ['United States', 329877505], ['India', 1326093247], ['Indonesia', 267026366], ['Bangladesh', 162650853], ['Pakistan', 233500636], ['Nigeria', 214028302], ['Brazil', 21171597], ['Russia', 141722205], ['Mexico', 128649565] ] Code language: Python (python)

Each element in a list is a tuple that contains the country’s name and population.

To get all the countries whose populations are greater than 300 million, you can use the filter() function as follows:

countries = [ ['China', 1394015977], ['United States', 329877505], ['India', 1326093247], ['Indonesia', 267026366], ['Bangladesh', 162650853], ['Pakistan', 233500636], ['Nigeria', 214028302], ['Brazil', 21171597], ['Russia', 141722205], ['Mexico', 128649565] ] populated = filter(lambda c: c[1] > 300000000, countries) print(list(populated)) Code language: Python (python)
[['China', 1394015977], ['India', 1326093247], ['United States', 329877505]]Code language: Python (python)

Summary

Источник

Читайте также:  Program log in java
Оцените статью