Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python itertools.compress() Function



The Pythonitertools.compress() function is used to filter elements from an iterable based on a corresponding selector iterable. It returns only those elements for which the corresponding value in the selector is True.

This function is useful when you need to selectively extract elements from an iterable based on predefined conditions.

Syntax

Following is the syntax of the Python itertools.compress() function −

itertools.compress(data, selectors)

Parameters

This function accepts the following parameters −

  • data: The iterable containing elements to be filtered.
  • selectors: An iterable of boolean values (or values evaluated as boolean). Elements indata are included only if the corresponding value inselectors is True.

Return Value

This function returns an iterator that produces elements fromdata where the corresponding value inselectors is True.

Example 1

Following is an example of the Python itertools.compress() function. Here, we filter a list of numbers based on a binary selector list −

import itertoolsdata = [1, 2, 3, 4, 5]selectors = [1, 0, 1, 0, 1]  # 1 means include, 0 means excludefiltered = itertools.compress(data, selectors)for item in filtered:   print(item)

Following is the output of the above code −

135

Example 2

Here, we use itertools.compress() function to filter a list of names based on a condition −

import itertoolsnames = ["Alice", "Bob", "Charlie", "David", "Eve"]selectors = [True, False, True, False, True]  # Only True values are includedfiltered_names = itertools.compress(names, selectors)for name in filtered_names:   print(name)

Output of the above code is as follows −

AliceCharlieEve

Example 3

Now, we generate the selectors dynamically using a condition. In this example, we filter numbers that are greater than 10 −

import itertoolsdata = [5, 12, 7, 20, 8, 15]selectors = [x > 10 for x in data]  # Generates [False, True, False, True, False, True]filtered_data = itertools.compress(data, selectors)for num in filtered_data:   print(num)

The result obtained is as shown below −

122015

Example 4

We can use itertools.compress() function with a mixed data type list to filter elements based on a custom condition. Here, we filter elements that are strings −

import itertoolsdata = ["apple", 42, "banana", 100, "cherry"]selectors = [isinstance(x, str) for x in data]  # Checks if each element is a stringfiltered_items = itertools.compress(data, selectors)for item in filtered_items:   print(item)

The result produced is as follows −

applebananacherry
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp