我有这样的一行:
filter(lambda x: x == 1, [1, 1, 2])
Pylint 显示警告:
W: 3: Used builtin function 'filter'
这是为什么?列表理解是推荐的方法吗?
当然我可以这样重写:
[x for x in [1, 1, 2] if x == 1]
而且我没有收到任何警告,但我想知道这是否有 PEP?
我有这样的一行:
filter(lambda x: x == 1, [1, 1, 2])
Pylint 显示警告:
W: 3: Used builtin function 'filter'
这是为什么?列表理解是推荐的方法吗?
当然我可以这样重写:
[x for x in [1, 1, 2] if x == 1]
而且我没有收到任何警告,但我想知道这是否有 PEP?
Pylint 经常喋喋不休地谈论不该谈论的事情。您可以在 .pylintrc 文件中禁用警告。
此页面http://pylint-messages.wikidot.com/messages:w0141表明问题在于过滤器和映射已被列表理解所取代。
在您的 pylintrc 文件中这样的一行将消除警告:
disable=W0141
这是为什么?列表理解是推荐的方法吗?
教程示例中建议使用列表理解,其中指出
它更简洁易读。
以及 SO's Python List Comprehension Vs上的大多数回答者。地图在哪里
filter
都定义 a更有效lambda
filter
filter
,map
如果你
map
,map
,或TL;DR:在大多数情况下使用列表推导
我遇到了同样的问题,无法弄清楚
为什么内置函数“输入”不好。我你打算
禁用它:
pylint --bad-functions="[map,filter,apply]" YOUR_FILE_TO_CHECK_HERE
一旦你喜欢这些设置:
pylint --bad-functions="[map,filter,apply]" --some-other-supercool-settings-of-yours
--generate-rcfile > test.rc
验证您的设置是否在文件中,例如:
cat test.rc | grep -i YOUR_SETTING_HERE
之后,您可以在本地使用此文件
pylint --rcfile test.rc --your-other-command-line-args ...
甚至将其用作您的默认 rcfile。为此,我请您参考
pylint --long-help
我的项目也收到了同样的警告。我正在将源代码更改为兼容 py2/3,而 pylint 有很大帮助。
运行pylint --py3k
仅显示有关兼容性的错误。
在 python 2 中,如果使用filter
,它返回一个list
:
>>> my_list = filter(lambda x: x == 1, [1, 1, 2])
>>> my_list
[1, 1]
>>> type(my_list)
<type 'list'>
但是在 python 3filter
和其他类似的方法(map
, range
, zip
, ..)返回一个迭代器,这是不兼容的类型,可能会导致代码中的错误。
>>> my_list = filter(lambda x: x == 1, [1, 1, 2])
>>> my_list
<filter object at 0x10853ac50>
>>> type(my_list)
<class 'filter'>
为了使您的代码与 python 2/3 兼容,我使用了来自python 未来站点的备忘单
为避免此警告,您可以使用 4 种适用于 python 2 和 3 的方法:
1 - 使用你说的列表理解。
2 - 使用一个list
函数,授予返回总是一个物化列表,两个python版本的结果相同
>>> list(filter(lambda x: x == 1, [1, 1, 2]))
[1, 1]
3 - 使用lfilter
,这是未来的包导入。它总是返回一个列表,在 py2 和list(filter(..)
py3 上使用过滤器。因此,两个 python 的行为相同,并且语法更清晰。
>>> from future.utils import lfilter
>>> lfilter(lambda x: x == 1, [1, 1, 2])
[1, 1]
4 - 最好的!始终在循环中使用filter
,这样 pylint 不会发出警告,并且它在 python 3 上具有很好的性能提升。
>>> for number in filter(lambda x: x == 1, [1, 1, 2]):
>>> print(number)
>>> 1
>>> 1
总是更喜欢在 python 3 上工作的函数,因为 python 2 很快就会退役。