unnecessary-map (C417)
Derived from the flake8-comprehensions linter. (源自 flake8-comprehensions linter。)
有时提供修复。
作用
检查使用 lambda 函数的不必要的 map()
调用。
为什么这不好?
当 func
是 lambda 时,使用 map(func, iterable)
比使用生成器表达式或推导式更慢,因为后一种方法避免了函数调用开销,并且更易于阅读。
此规则也适用于 list()
、set()
和 dict()
调用中的 map()
调用。例如
- 使用
[num * 2 for num in nums]
而不是list(map(lambda num: num * 2, nums))
。 - 使用
{num % 2 == 0 for num in nums}
而不是set(map(lambda num: num % 2 == 0, nums))
。 - 使用
{v: v ** 2 for v in values}
而不是dict(map(lambda v: (v, v ** 2), values))
。
示例
建议改为
修复安全性
This rule's fix is marked as unsafe, as it may occasionally drop comments when rewriting the call. In most cases, though, comments will be preserved. (此规则的修复被标记为不安全,因为它在重写调用时有时会删除注释。但在大多数情况下,注释将被保留。)