Python Glossary Русский

all Python 3itertoolsfunction

itertools.compress

itertools

Select elements of data where the corresponding selector is true.

Syntax

itertools.compress(data, selectors)

It stops at the shorter of the two arguments and ignores the leftover tail. It shines when you already have a boolean mask computed elsewhere and want to reuse it — cleaner than a comprehension zipping the two — and selectors can be any truthy/falsy values, not just 0 and 1.

Examples

import itertools
print(list(itertools.compress(['a', 'b', 'c', 'd'], [1, 0, 1, 0])))   # → ['a', 'c']
nums = [5, 12, 7, 20]
print(list(itertools.compress(nums, [n > 10 for n in nums])))   # → [12, 20]
print(list(itertools.compress([1, 2, 3], [1, 1])))   # → [1, 2]
print(list(itertools.compress(['a', 'b', 'c'], ['', 'x', None])))   # → ['b']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy