Following system colour scheme - Python 增强提案 Selected dark colour scheme - Python 增强提案 Selected light colour scheme - Python 增强提案

Python 增强提案

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 版本中成为 Python 语言的一部分,具体文档见 [1]

BDFL 公告

  • 上述提出的语法是正确的。
  • 形式 [x, y for ...] 是不允许的;必须写成 [(x, y) for ...]
  • 形式 [... for x... for y...] 是嵌套的,最后一个索引变化最快,就像嵌套的 for 循环一样。

参考资料


来源:https://github.com/python/peps/blob/main/peps/pep-0202.rst

最后修改:2025-02-01 08:55:40 GMT