2015-10-16 62 views
17

使用Python IDLE 3.5.0 shell。根据我对内置“过滤器”函数的理解,它将返回一个列表,元组或字符串,具体取决于您传递给它的内容。那么,为什么下面工作的第一项任务,而不是第二(以下简称“>>>的仅仅是交互式Python提示)为什么foo = filter(...)返回一个<过滤器对象>,而不是一个列表?

>>> def greetings(): 
    return "hello" 

>>> hesaid = greetings() 
>>> print(hesaid) 
hello 
>>> 
>>> shesaid = filter(greetings(), ["hello", "goodbye"]) 
>>> print(shesaid) 
<filter object at 0x02B8E410> 
+2

我的机器上,'帮助(过滤器)'说,它返回一个迭代器,而不是一个列表或元组或字符串。您可能正在查看旧版Python的文档。无论如何,即使在旧版本中,你的'filter'表达式也不起作用,因为'filter'的第一个参数必须是可调用的,'greetings()'返回的值不是可调用的。 – Kevin

+0

我正在使用一个旧的教程,它没有声明Python的版本。谢谢凯文......虽然我不明白(刚开始这里: - )......你这里的意思是:“因为过滤器的第一个参数必须是可调用的,并且由greetings()返回的值不是一个可调用的“。 – Margarita

+0

你已经让我自学了下一个可以召唤的东西..已经在论坛和其他地方发现了一些主题。再次感谢! (试图编辑以前的评论,但StackOverflow不允许... – Margarita

回答

22

看看filter(function, iterable)(来自here)的python文档:

迭代那些元件为其功能返回true构建的迭代器。

所以得到一个列表,你必须使用:

shesaid = list(filter(greetings(), ["hello", "goodbye"])) 

但是,这可能不是你想要的东西,因为它试图调用greetings()的结果,这是“你好”,在你的输入列表的值,这是行不通的。在这里迭代器类型也会起作用,因为在使用它们之前不会生成结果(例如通过调用list())。所以一开始你不会得到一个错误,但是当你尝试做一些与shesaid它就会停止工作:

>>> print(list(shesaid)) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: 'str' object is not callable 

如果您要检查其在列表中的元素都等于“你好“你必须使用这样的事情:

shesaid = list(filter(lambda x: x == "hello", ["hello", "goodbye"])) 

(我把你的功能为lambda,看到兰迪C'S答案是‘正常’的功能)

+0

谢谢,这真的很有帮助和清楚 – Margarita

+0

请注意,由于()',第一个'shesaid'行*不会*调用'greetings'你的输入列表的值 - 它试图调用'greetings()'返回的值,所以它试图调用''hello''(字符串),就像它是一个函数一样 – DSM

+0

谢谢帝斯曼, - yep ,你的评论确认了TobiMarg的回应给我的确切理解。清除......一旦得到它!:-) – Margarita

4

过滤器期望得到的功能和东西,它可以遍历。该函数应该为迭代器中的每个元素返回True或False。在您的具体的例子,你希望做的是类似如下:

In [47]: def greetings(x): 
    ....:  return x == "hello" 
    ....: 

In [48]: filter(greetings, ["hello", "goodbye"]) 
Out[48]: ['hello'] 

注意的是Python 3,则可能需要使用list(filter(greetings, ["hello", "goodbye"]))得到这个相同的结果。

1

从文档

注意filter(function, iterable)相当于[item for item in iterable if function(item)]

在python3,而不是返回一个列表;过滤器,映射返回一个迭代。你的尝试应该在python2上工作,但不能在python3上运行。

显然,你正在获得一个过滤器对象,使它成为一个列表。

shesaid = list(filter(greetings(), ["hello", "goodbye"])) 
1

请参阅的filter这个样例实现以了解它是如何工作在Python 3:

def my_filter(function, iterable): 
    """my_filter(function or None, iterable) --> filter object 

    Return an iterator yielding those items of iterable for which function(item) 
    is true. If function is None, return the items that are true.""" 
    if function is None: 
     return (item for item in iterable if item) 
    return (item for item in iterable if function(item)) 

以下是如何使用filtermy_filter发电机为例:

>>> greetings = {'hello'} 
>>> spoken = my_filter(greetings.__contains__, ('hello', 'goodbye')) 
>>> print('\n'.join(spoken)) 
hello 
0

之所以返回< filter object >是,过滤器是类而不是内置函数。

help(filter)你会得到如下:在模块内建 帮助阶级过滤器:

class filter(object) 
| filter(function or None, iterable) --> filter object 
| 
| Return an iterator yielding those items of iterable for which function(item) 
| is true. If function is None, return the items that are true. 
| 
| Methods defined here: 
| 
| __getattribute__(self, name, /) 
|  Return getattr(self, name). 
| 
| __iter__(self, /) 
|  Implement iter(self). 
| 
| __new__(*args, **kwargs) from builtins.type 
|  Create and return a new object. See help(type) for accurate signature. 
| 
| __next__(self, /) 
|  Implement next(self). 
| 
| __reduce__(...) 
|  Return state information for pickling. 
相关问题