代码之家  ›  专栏  ›  技术社区  ›  igorgue

为什么Pylint不喜欢内置函数?

  •  72
  • igorgue  · 技术社区  · 14 年前

    我有这样一句话:

    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]
    

    我没有收到任何警告,但我想知道是否有人为此打气?

    4 回复  |  直到 14 年前
        1
  •  96
  •   Ned Batchelder    10 年前

    Pylint经常喋喋不休地谈论它不应该谈论的东西。您可以在.pylintrc文件中禁用警告。

    http://pylint-messages.wikidot.com/messages:w0141 表示问题是筛选器和映射已被列表理解取代。

    disable=W0141
    
        2
  •  11
  •   Community CDub    8 年前

    为什么?列表理解是推荐的方法吗?

    列表理解建议在 the tutorial example

    它更简洁易读。

    大多数回答者都这么说 Python List Comprehension Vs. Map 哪里 it is

    1. 效率更高 filter 如果您正在定义 lambda 每次
    2. 也许 吧 更具可读性 (并以类似的效率)使用 滤波器
    3. 必须使用 滤波器 map
      • 地图 地图
      • 咖喱 地图 ,或

    TL;DR:在大多数情况下使用列表理解

        3
  •  5
  •   benjamin    11 年前

    我遇到了同样的问题,搞不懂

    pylint—坏函数=“[map,filter,apply]”您的\u文件要\u在这里检查\u

    一旦您喜欢这些设置:

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

    甚至可以将其用作默认文件。为此,我恳请你

    pylint --long-help
    
        4
  •  1
  •   Jorge Continuous    6 年前

    我的项目也收到了同样的警告。我将源代码改为py2/3兼容,pylint帮助很大。

    pylint --py3k 仅显示有关兼容性的错误。

    在python2中,如果使用 filter list :

    >>> my_list = filter(lambda x: x == 1, [1, 1, 2])
    >>> my_list
    [1, 1]
    >>> type(my_list)
    <type 'list'>
    

    滤波器 map , range , zip ,..)返回一个迭代器,它是不兼容的类型,可能会导致代码中出现错误。

    >>> my_list = filter(lambda x: x == 1, [1, 1, 2])
    >>> my_list
    <filter object at 0x10853ac50>
    >>> type(my_list)
    <class 'filter'>
    

    为了使您的代码与python2/3兼容,我使用了 python future site

    为了避免此警告,您可以使用4种方法,它们适用于Python2和Python3:

    1-使用你说的列表理解。

    函数,授予返回的总是一个具体化的列表,结果在两个python版本上是相同的

    >>> list(filter(lambda x: x == 1, [1, 1, 2]))
    [1, 1]
    

    3-使用 lfilter list(filter(..)

    >>> from future.utils import lfilter
    >>> lfilter(lambda x: x == 1, [1, 1, 2])
    [1, 1]
    

    >>> for number in filter(lambda x: x == 1, [1, 1, 2]):
    >>>     print(number)
    >>> 1
    >>> 1
    

    总是喜欢在Python3上工作的函数,因为Python2很快就会退役。