Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

2. itertools.compress(): A Convenient Way To Filter Data

Sumit Rawal answered on May 13, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers

  • 9. itertools.takewhile(): Filter Elements in a Different Way

  • 2. itertools.compress(): A Convenient Way To Filter Data

    0

    We can filter a list of items through one or a few loops for sure.

    But sometimes, we may not need to write any loops. Cause there is a function named itertools.compress().

    The itertools.compress() function returns an iterator that filters an iterable based on the values of a corresponding boolean mask.

    For example, the following code selects the true leaders using the itertools.compress() function:

    import itertools

    leaders = ['Yang', 'Elon', 'Tim', 'Tom', 'Mark']

    selector = [1, 1, 0, 0, 0]

    print(list(itertools.compress(leaders, selector)))

    # ['Yang', 'Elon']

    The second argument, selector, works as a mask, we can also define it as follows:

    selector = [True, True, False, False, False]  

    Popularity 1/10 Helpfulness 1/10 Language whatever
    Source: Grepper
    Link to this answer
    Share Copy Link
    Contributed on May 13 2023
    Sumit Rawal
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.