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

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

问题描述

在Python IDLE 3.5.0 shell中工作。根据我对内置过滤器函数的理解,它返回一个列表,元组或字符串,具体取决于你传入的内容。那么,为什么下面的第一个赋值工作,而不是第二个赋值(>>>只是交互式的Python提示符)

 >>> def greetings():
returnhello

>>> hesaid = greetings()
>>>打印(hesaid)
hello
>>>
>>> shesaid = filter(greetings(),[hello,goodbye])
>>> print(shesaid)
< 0x02B8E410的过滤器对象>


解决方案

$ c> filter(function,iterable)(来自这里
$ b


iterable 的元素构造一个迭代器, / em>返回true。


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

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

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

 >>> print(list(shesaid))
Traceback(最近一次调用最后一次):
在< module>中的第1行文件< stdin>
TypeError:'str'对象不可调用






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

  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 the get a list back you have to use:

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天全站免登陆