python - Python 3 中的过滤对象错误

标签 python python-2.7 python-3.x lambda filter

当我在 Python 3 中运行这段代码时:

languages = ["HTML", "JavaScript", "Python", "Ruby"]
print( filter(lambda x: x == "Python",languages))

我收到这个错误:

filter object at 0x7fd83ff0
filter object at 0x7feede10

我不知道这个错误是什么意思——它在 Python 2.7 中运行正常。

谁能提出解决方案?

最佳答案

这不是错误 - 你打印了一个 过滤器类型的对象 因为 filter() 不返回 list - 它 < em>构造一个迭代器,但仅当有对它的请求时

最简单的解决方案是使用函数 list() - 它请求一个迭代器并返回列表:

print( list(filter(lambda x: x == "Python", languages)))

代替你的命令

print( filter(lambda x: x == "Python",languages))

注意:类似于打印range(10)(是一个对象)和打印list(range(10)) (这是列表)。

Python 2.xPython 3.x 之间,几乎所有在 Python 2.x 中返回 list 的函数都有变化- 在 Python 3.x 中,它们返回更通用且内存消耗更少的内容,例如如何在感兴趣的情况下获取元素的方法

比较:1、2、3、4、5、6、7、8、91 到 9 的整数(或 1、2 , ..., 9).
没有区别?尝试写下从 1 到 999999 的所有整数

关于python - Python 3 中的过滤对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867002/

相关文章:

python - Pandas - 按日期对日内时间序列进行分组

python - 如何重新采样并将值计数为新的列标题并计数为它的值

python更新列表中的字典值

python - 使用 Python 将 "entry"添加到 JSON 文件

python - 程序在 if while 使用循环之后结束,但它不应该结束

python - 如何找到列表中特定元素的位置?

python - Python Fabric 函数的直接输出到远程主机上的文件

python-2.7 - Tensorflow(python):train_step.run(…)中的“ValueError:设置具有序列的数组元素”

Python从字符串列表中获取一个元素

python - 为什么自定义对象在 python 中是可哈希的(并且可以在 dict 中使用)?