简体   繁体   English

有人可以为我解释这个 filter() 函数吗?

[英]can someone explain this filter() function for me?

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?为什么 man 可以这样编写filter()函数? 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.每个filter采用一个谓词(确定元素是否为成员的函数),但有两个过滤器。 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.首先, L不应该是异质的。 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.在这里,我还使用isinstance在一次调用中检查任一类型,而不是通过相等性比较type(x)两次。

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.您的函数不应该在处理对象之前测试类型——它应该尽可能是类型安全的,即使在 Python 中也是如此。

The filter() method takes two parameters: filter()方法有两个参数:

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 function - 测试可迭代元素是否返回 true 或 false 的函数 如果None ,则该函数默认为 Identity 函数 - 如果任何元素为 false 则返回 false

iterable - iterable which is to be filtered, could be sets, lists, tuples, or containers of any iterators. iterable - 要过滤的可迭代对象,可以是任何迭代器的集合、列表、元组或容器。

The filter() method returns iterable. filter()方法返回可迭代的。

In your case the function is defined as a lambda which checks if the number is even ( lambda x: x%2==0 ).在您的情况下,该函数被定义为一个 lambda,它检查数字是否为偶数( lambda x: x%2==0 )。 The iterable is filtered against the type, accepting only integers and floats.可迭代对象根据类型进行过滤,仅接受整数和浮点数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM