PEP 202 – 列表推导式
- 作者:
- Barry Warsaw <barry at python.org>
- 状态:
- 最终
- 类型:
- 标准跟踪
- 创建:
- 2000年7月13日
- Python 版本:
- 2.0
- 历史记录:
简介
本 PEP 描述了对 Python 的一项提议的语法扩展,即列表推导式。
提议的解决方案
提议允许使用 for 和 if 子句以条件方式构建列表字面量。它们的嵌套方式与 for 循环和 if 语句目前的嵌套方式相同。
基本原理
列表推导式提供了一种更简洁的方式来创建列表,在当前使用 map()
和 filter()
和/或嵌套循环的情况下。
示例
>>> print [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print [i for i in range(20) if i%2 == 0]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> nums = [1, 2, 3, 4]
>>> fruit = ["Apples", "Peaches", "Pears", "Bananas"]
>>> print [(i, f) for i in nums for f in fruit]
[(1, 'Apples'), (1, 'Peaches'), (1, 'Pears'), (1, 'Bananas'),
(2, 'Apples'), (2, 'Peaches'), (2, 'Pears'), (2, 'Bananas'),
(3, 'Apples'), (3, 'Peaches'), (3, 'Pears'), (3, 'Bananas'),
(4, 'Apples'), (4, 'Peaches'), (4, 'Pears'), (4, 'Bananas')]
>>> print [(i, f) for i in nums for f in fruit if f[0] == "P"]
[(1, 'Peaches'), (1, 'Pears'),
(2, 'Peaches'), (2, 'Pears'),
(3, 'Peaches'), (3, 'Pears'),
(4, 'Peaches'), (4, 'Pears')]
>>> print [(i, f) for i in nums for f in fruit if f[0] == "P" if i%2 == 1]
[(1, 'Peaches'), (1, 'Pears'), (3, 'Peaches'), (3, 'Pears')]
>>> print [i for i in zip(nums, fruit) if i[0]%2==0]
[(2, 'Peaches'), (4, 'Bananas')]
参考实现
列表推导式成为 Python 语言 2.0 版本的一部分,并在 [1] 中进行了说明。
BDFL 声明
- 上面提议的语法是正确的。
- 形式
[x, y for ...]
不允许;需要编写[(x, y) for ...]
。 - 形式
[... for x... for y...]
嵌套,最后一个索引变化最快,就像嵌套的 for 循环一样。
参考文献
来源: https://github.com/python/peps/blob/main/peps/pep-0202.rst
上次修改: 2023-09-09 17:39:29 GMT