Movatterモバイル変換


[0]ホーム

URL:


Following system colour schemeSelected dark colour schemeSelected light colour scheme

Python Enhancement Proposals

PEP 202 – List Comprehensions

Author:
Barry Warsaw <barry at python.org>
Status:
Final
Type:
Standards Track
Created:
13-Jul-2000
Python-Version:
2.0
Post-History:


Table of Contents

Introduction

This PEP describes a proposed syntactical extension to Python, listcomprehensions.

The Proposed Solution

It is proposed to allow conditional construction of list literals using for andif clauses. They would nest in the same way for loops and if statements nestnow.

Rationale

List comprehensions provide a more concise way to create lists in situationswheremap() andfilter() and/or nested loops would currently be used.

Examples

>>>print[iforiinrange(10)][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>>print[iforiinrange(20)ifi%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)foriinnumsforfinfruit][(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)foriinnumsforfinfruitiff[0]=="P"][(1, 'Peaches'), (1, 'Pears'), (2, 'Peaches'), (2, 'Pears'), (3, 'Peaches'), (3, 'Pears'), (4, 'Peaches'), (4, 'Pears')]>>>print[(i,f)foriinnumsforfinfruitiff[0]=="P"ifi%2==1][(1, 'Peaches'), (1, 'Pears'), (3, 'Peaches'), (3, 'Pears')]>>>print[iforiinzip(nums,fruit)ifi[0]%2==0][(2, 'Peaches'), (4, 'Bananas')]

Reference Implementation

List comprehensions become part of the Python language with release 2.0,documented in[1].

BDFL Pronouncements

  • The syntax proposed above is the Right One.
  • The form[x,yfor...] is disallowed; one is required to write[(x,y)for...].
  • The form[...forx...fory...] nests, with the last indexvarying fastest, just like nested for loops.

References

[1]
http://docs.python.org/reference/expressions.html#list-displays

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

Last modified:2025-02-01 08:55:40 GMT


[8]ページ先頭

©2009-2025 Movatter.jp