为什么 foo = filter(...) 返回一个 <filter object>,而不是一个列表? [英] Why does foo = filter(...) return a <filter object>, not a list?

查看:25
本文介绍了为什么 foo = filter(...) 返回一个 <filter object>,而不是一个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python IDLE 3.5.0 shell 中工作.根据我对内置过滤器"函数的理解,它返回列表、元组或字符串,具体取决于您传递给它的内容.那么,为什么下面的第一个任务有效,而第二个任务无效('>>>'s 只是交互式 Python 提示)

<预><代码>>>>定义问候():回复你好">>>hesaid = 问候()>>>打印(他说)你好>>>>>>shesaid = 过滤器(问候(),[你好",再见"])>>>打印(她说)<过滤器对象在 0x02B8E410>

解决方案

查看 Python 文档 filter(function, iterable)(来自 这里):

<块引用>

iterable 的那些function 返回 true 的元素构造一个迭代器.

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

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

但这可能不是您想要的,因为它试图在您的输入列表的值上调用 greetings() 的结果,即hello",而这不会工作.在这里,迭代器类型也开始发挥作用,因为在您使用结果之前不会生成结果(例如通过调用 list() 对其).所以一开始你不会得到错误,但是当你尝试用 shesaid 做某事时它会停止工作:

<预><代码>>>>打印(列表(她说))回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:str"对象不可调用

<小时>

如果你想检查列表中哪些元素等于hello",你必须使用这样的东西:

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

(我将您的函数放入 lambda,请参阅 Randy C 对正常"函数的回答)

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)

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

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

解决方案

Have a look at the python documentation for filter(function, iterable) (from here):

Construct an iterator from those elements of iterable for which function returns 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:

>>> 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:

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)

这篇关于为什么 foo = filter(...) 返回一个 &lt;filter object&gt;,而不是一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆