Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter Python 2D Array based on 2nd Element

I have a python 2D array like this:

array = [('aaa', 20), ('bbb', 30), ('ccc', 40), ('ddd', 50)]

I want to filter this array based on the 2nd value in each set.
for example I want to keep only the items having the 2nd item >= 40

Expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

filtered_array =  [('ccc', 40), ('ddd', 50)]

I can achieve this with loops but is there an elegant way of filtering this?

>Solution :

Clearest:

[x for x in xs if x[1] >= 40]

Less clear:

list(filter(lambda x: x[1] >= 40, xs))

No loops at the Python level:

def f(xs):
    try:
        x = next(xs)
    except StopIteration:
        return
    if x[1] >= 40:
        yield x
    yield from f(xs)

list(f(iter(xs)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading