使用Python IDLE 3.5.0 shell。根据我对内置“过滤器”函数的理解,它会返回列表,元组或字符串,具体取决于您传入的内容。那么,为什么下面的第一个分配工作,而不是第二个('>>>'只是交互式Python提示)
>>> def greetings():
return "hello"
>>> hesaid = greetings()
>>> print(hesaid)
hello
>>>
>>> shesaid = filter(greetings(), ["hello", "goodbye"])
>>> print(shesaid)
<filter object at 0x02B8E410>
答案 0 :(得分:51)
查看filter(function, iterable)
的python文档(来自here):
从 iterable 的那些元素构造一个迭代器,其中 function 返回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,参见Randy C对“正常”函数的回答)
答案 1 :(得分:6)
filter期望得到一个函数和它可以迭代的东西。对于iterable中的每个元素,该函数应返回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"]))
来获得相同的结果。
答案 2 :(得分:2)
请参阅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))
以下是如何使用filter
或my_filter
生成器的示例:
>>> greetings = {'hello'}
>>> spoken = my_filter(greetings.__contains__, ('hello', 'goodbye'))
>>> print('\n'.join(spoken))
hello
答案 3 :(得分:1)
来自文档
请注意,
filter(function, iterable)
相当于[item for item in iterable if function(item)]
在python3中,而不是返回列表; filter,map返回一个iterable。你的尝试应该适用于python2但不适用于python3
显然,您正在获取过滤器对象,将其设为列表。
shesaid = list(filter(greetings(), ["hello", "goodbye"]))
答案 4 :(得分:0)
返回< filter object >
的原因是,filter是class而不是内置函数。
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.