Python Filter Not Working As Expected?
Why do the following two filter expressions return the same result? A = [(1,(1,2,3))] A1 = filter(lambda (a,b): b, A) A2 = filter(lambda ab: ab, A) A1 == A2 >>>> True
Solution 1:
filter
filters out arguments that when passed into the function, returns a False
-ish value. Both (1, 2, 3)
and (1, (1, 2, 3))
return True
in a boolean context, and therefore remain in the returned list.
You want map
instead.
A1 = map(lambda (a,b): b, A)
A2 = map(lambda ab: ab, A)
FYI, the follwing values are False
-ish values, while everything else is True
-ish:
0NoneFalse''
[]
()
# and all other empty containers
Solution 2:
It's not a bug. filter
takes elements where your function returns True
-y values.
In the first case, you unpack the tuple as 1
and (1,2,3)
and you look at the second one ((1,2,3)
) -- It's true (non-empty), so filter
returns the whole thing.
In the second case, you look at the tuple (1,(1,2,3))
. That's not empty either, so it returns the whole thing again.
Post a Comment for "Python Filter Not Working As Expected?"