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?
>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)))