Python具有filter方法,该方法根据某些条件过滤所需的输出,如以下示例所示。
>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'
该示例取自link。现在,当我尝试在Python IDE中执行类似操作时,它实际上会返回结果,'somestring. with funny characters'
并返回this <filter object at 0x0000020E1792EC50>
。在IDE中,我不能仅使用简单的Enter键,因此在过滤时,我将使用打印运行整个代码。我在哪里做错了?谢谢。
在python3中,过滤器返回一个生成器(请参阅docs)
因此,您通常希望将其转换为列表以查看其内容,或者在您的情况下为字符串:
>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> f = filter(lambda x: x in printable, s)
>>> ''.join(f)
'somestring. with funny characters'
filter
成为迭代器的好处是它使用更少的内存。它也可以像列表一样轻松地循环播放。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句