Home > Blockchain >  Filter Python 2D Array based on 2nd Element
Filter Python 2D Array based on 2nd Element

Time:11-04

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:

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

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

CodePudding user response:

You can use filter, but under the hood, it still uses a loop, because how else?

list(filter(lambda x: x[1] >= 40, array))
#[('ccc', 40), ('ddd', 50)]

Or you can use itertools.filterfalse (with the same footnote):

list(itertools.filterfalse(lambda x: x[1] < 40, array))
#[('ccc', 40), ('ddd', 50)]

CodePudding user response:

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)))
  • Related