gpt4 book ai didi

python - 为什么 foo = filter(...) 返回一个 ,而不是一个列表?

转载 作者:IT老高 更新时间:2023-10-28 20:35:33 25 4
gpt4 key购买 nike

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

最佳答案

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

Construct an iterator from those elements of iterable for which function returns true.

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

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

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

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

如果您想检查列表中的哪些元素等于“hello”,您必须使用以下内容:

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

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

关于python - 为什么 foo = filter(...) 返回一个 <filter object>,而不是一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33174276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com