def only_even(L):
return list(filter(lambda x: x%2==0,filter(lambda x:type(x) == int or type(x) == float,L)))
a = only_even([1,2,3,46,"String", "noch ein String", 2.0, True, [2,4]])
print(a)
why can man write the filter()
function like this? the first parameter takes two funktion as arguments
Each filter
is taking one predicate (the function determining whether the element is a member or not), but there are two filters. This is equivalent to:
numbers = filter(lambda x: type(x) == int or type(x) == float, L)
return list(filter(lambda x: x%2 == 0, numbers))
It is, however, incredibly awful. First of all, L
should not be heterogenous. If it is, we've probably done something Bad elsewhere in the codebase. Even if that were the case, since we're casting to list afterwards we should just use a list comprehension to begin with.
return [x for x in L if isinstance(x, (int, float)) and x%2==0]
Here I also use isinstance
to check for either type in one call rather than comparing type(x)
by equality twice.
Alternatively, you could write this explicitly, which is less terse but more easily readable
evens = []
for candidate in L:
try:
if candidate % 2 == 0:
evens.append(candidate)
except TypeError:
# "candidate" is not a number -- ignore it
pass
return evens
However I must stress that code like this is the sign of something having gone wrong elsewhere in the code base. Your function should not have to test type before handling the object -- it should be type safe wherever possible, even in Python.
The filter()
method takes two parameters:
function - function that tests if elements of an iterable returns true or false If None
, the function defaults to Identity function - which returns false if any elements are false
iterable - iterable which is to be filtered, could be sets, lists, tuples, or containers of any iterators.
The filter()
method returns iterable.
In your case the function is defined as a lambda which checks if the number is even ( lambda x: x%2==0
). The iterable is filtered against the type, accepting only integers and floats.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.