Python 为什么 foo = filter(...) 返回一个 <filter object>,而不是一个列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33174276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does foo = filter(...) return a <filter object>, not a list?
提问by Margarita
Working in Python IDLE 3.5.0 shell. From my understanding of the builtin "filter" function it returns either a list, tuple, or string, depending on what you pass into it. So, why does the first assignment below work, but not the second (the '>>>'s are just the interactive Python prompts)
在 Python IDLE 3.5.0 shell 中工作。根据我对内置“过滤器”函数的理解,它返回列表、元组或字符串,具体取决于您传递给它的内容。那么,为什么下面的第一个作业有效,而第二个无效('>>>'s 只是交互式 Python 提示)
>>> def greetings():
return "hello"
>>> hesaid = greetings()
>>> print(hesaid)
hello
>>>
>>> shesaid = filter(greetings(), ["hello", "goodbye"])
>>> print(shesaid)
<filter object at 0x02B8E410>
采纳答案by TobiMarg
Have a look at the python documentation for filter(function, iterable)
(from here):
查看 Python 文档filter(function, iterable)
(来自此处):
Construct an iterator from those elements of iterablefor which functionreturns true.
从构造的那些元件的迭代器可迭代为哪些函数返回真。
So in order to get a list back you have to use list class:
所以为了得到一个列表,你必须使用列表类:
shesaid = list(filter(greetings(), ["hello", "goodbye"]))
But this probably isn't what you wanted, because it tries to call the result of greetings()
, which is "hello", on the values of your input list, and this won't work. Here also the iterator type comes into play, because the results aren't generated until you use them (for example by calling list()
on it). So at first you won't get an error, but when you try to do something with shesaid
it will stop working:
但这可能不是您想要的,因为它试图greetings()
在输入列表的值上调用 的结果,即“hello”,但这是行不通的。迭代器类型也在这里发挥作用,因为直到您使用它们(例如通过调用list()
它)才会生成结果。所以一开始你不会得到错误,但是当你尝试用shesaid
它做一些事情时会停止工作:
>>> print(list(shesaid))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
If you want to check which elements in your list are equal to "hello" you have to use something like this:
如果您想检查列表中的哪些元素等于“hello”,您必须使用以下内容:
shesaid = list(filter(lambda x: x == "hello", ["hello", "goodbye"]))
(I put your function into a lambda, see Randy C's answer for a "normal" function)
(我将您的函数放入 lambda 中,请参阅 Randy C 对“正常”函数的回答)
回答by Randy
filter expects to get a function and something that it can iterate over. The function should return True or False for each element in the iterable. In your particular example, what you're looking to do is something like the following:
filter 期望得到一个函数和它可以迭代的东西。该函数应该为迭代中的每个元素返回 True 或 False。在您的特定示例中,您要执行的操作如下所示:
In [47]: def greetings(x):
....: return x == "hello"
....:
In [48]: filter(greetings, ["hello", "goodbye"])
Out[48]: ['hello']
Note that in Python 3, it may be necessary to use list(filter(greetings, ["hello", "goodbye"]))
to get this same result.
请注意,在 Python 3 中,可能需要使用list(filter(greetings, ["hello", "goodbye"]))
来获得相同的结果。
回答by Ahsanul Haque
From the documentation
从文档
Note that
filter(function, iterable)
is equivalent to[item for item in iterable if function(item)]
请注意,
filter(function, iterable)
相当于[item for item in iterable if function(item)]
In python3, rather than returning a list; filter, map return an iterable. Your attempt should work on python2 but not in python3
在python3中,而不是返回一个列表;过滤器,映射返回一个可迭代对象。您的尝试应该适用于 python2 但不适用于 python3
Clearly, you are getting a filter object, make it a list.
显然,您正在获取一个过滤器对象,将其设为列表。
shesaid = list(filter(greetings(), ["hello", "goodbye"]))
回答by Noctis Skytower
Please see this sample implementation of filter
to understand how it works in Python 3:
请参阅此示例实现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))
The following is an example of how you might use filter
or my_filter
generators:
以下是您可能如何使用filter
或my_filter
生成器的示例:
>>> greetings = {'hello'}
>>> spoken = my_filter(greetings.__contains__, ('hello', 'goodbye'))
>>> print('\n'.join(spoken))
hello
回答by JordanChina
the reason why it returns < filter object >
is that, filter is class instead of built-in function.
它返回的原因< filter object >
是,过滤器是类而不是内置函数。
help(filter)
you will get following:
Help on class filter in module builtins:
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.