Python 的列表推导式在其他语言中也有类似实现。JavaScript 使用 Array.map() + Array.filter() 实现类似效果。来看相同逻辑在两种语言中的写法对比:
| | |
|---|
| | |
| | |
| | a.filter(x=>x>0).map(x=>x*2) |
| [f(x,y) for x in a for y in b] | a.flatMap(x=>b.map(y=>f(x,y))) |
下面是相同功能在 JavaScript 中的完整实现,可以看到 map + filter 的链式调用风格:
// 等价于 Python 的 [x*2 for x in nums if x > 0]const nums = [-3, -1, 0, 2, 4, -5]; const result = nums .filter(x => x > 0) .map(x => x * 2); console.log(result); // [4, 8]
最后,用一段 Shell 命令快速验证推导式的性能优势:
python3 -m timeit "[x**2 for x in range(1000)]"python3 -m timeit "list(map(lambda x: x**2, range(1000)))"