我的项目也收到了同样的警告。我正在将源代码更改为兼容 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 3 中,filter 和其他类似方法(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 future site 的备忘单
为避免此警告,您可以使用 4 种适用于 python 2 和 3 的方法:
1 - 使用你所说的列表理解。
2 - 使用list 函数,授予返回总是一个物化列表,两个python版本的结果相同
>>> list(filter(lambda x: x == 1, [1, 1, 2]))
[1, 1]
3 - 使用lfilter,这是未来的包导入。它总是返回一个列表,在 py2 上使用过滤器,在 py3 上使用list(filter(..)。因此,两个 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 很快就会被淘汰。