Share to: share facebook share twitter share wa share telegram print page

列表推导式

列表推导式(list comprehension),是程序设计语言的一类语法结构,用于基于描述创建一个列表(list)数据结构。相当于数学上的集合建構式符號。但不同于mapfilter函数。

“list comprehension”没有统一的中文译法。有译作列表解析式、列表生成式、列表构建、列表理解等。

概述

考虑下述集合建構式符號

可读作:“是所有“”的数的集合,满足是自然数,并且的平方大于。”

  • 是表示输入集合的成员的变量。
  • 表示输入集合,这里是自然数
  • 谓词表示式,用于从输入集筛选。
  • 是输出表达式,用于产生新的集合。
  • 花括号表示输出值组成集合。
  • 竖杠读作“满足”,可以同冒号“:”互换使用。
  • 逗号分隔谓词,可以读作“并且”。

列表推导式,与从一个输入列表迭代器,依次生成一个列表的表示,有相同的语法构件:

  • 代表输入列表的成员的一个变量。
  • 一个输入列表(或迭代器)。
  • 一个可选的谓词(判断)表达式。
  • 和从满足这个判断的,输入可迭代者的成员,产生输出列表的成员的一个表达式。

Haskell的列表推导式语法中,上述集合建造结构类似的写为如下:

s = [ 2*x | x <- [0..], x^2 > 3 ]

这里的列表[0..]表示x^2 > 3表示谓词,而2*x表示输出表达式。列表推导式,按一个确定次序,给出结果(不同于集合的成员);并且列表推导式,可以依次生成一个列表的成员,而非生成这个列表的全体,从而允许前面的对一个无穷列表的成员的Haskell定义。

历史

在术语“列表推导式”使用之前,就存在了有关的构造。集合论编程语言SETL(1969年),有类似列表推导式的一种形成构造。比如,这个代码打印从2N的所有素数:

print([n in [2..N] | forall m in {2..n - 1} | n mod m > 0]);

计算机代数系统AXIOM英语Axiom (computer algebra system)(1973年),有处理串流的类似构造。

首次对这种构造的使用术语“推导式”,是在1977年以后,Rod Burstall英语Rod Burstall和John Darlington,用在他们的函数式编程语言NPL的描述之中。在David Turner英语David Turner (computer scientist)的回忆录《函数式编程语言的一些历史》中,他回想起[1]

NPL由Burstall用POP2实现,并被Darlington用于程序变换的工作(Burstall & Darlington 1977)。这个语言,是一阶、强类型(但不多态)、纯函数式、传值调用的。它还有“集合表达式”比如:
setofeven (X)  <=  <:x : x in X & even(x):>

在给术语“列表推导式”附加的脚注中,Turner还记述了:

我最初称其为“ZF表达式”,参照了Zermelo-Frankel集合论Phil Wadler铸就了更好的术语“列表推导式”。

Burstall和Darlington关于NPL的工作,在1980年代影响了很多函数式编程语言,但并非全部都包括了列表推导式。其中最有影响的,是1985年发行的,Turner的惰性纯函数式编程语言Miranda。后来开发的标准惰性纯函数式语言Haskell,包含了Miranda的很多特征,包括列表推导式。

Python示例

Python语言的列表推导式和生成器表达式的语法示例:

>>> s = [2*x for x in range(10) if x**2 > 3]
>>> print(s)
[4, 6, 8, 10, 12, 14, 16, 18]
>>> from itertools import count, islice
>>> s = (2*x for x in count(0) if x**2 > 3)
>>> t = islice(s, 10)
>>> print([*t])
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
>>> print([*t])
[]
>>> t = islice(s,10)
>>> print([*t])
[24, 26, 28, 30, 32, 34, 36, 38, 40, 42]

推广

并行列表推导式

格拉斯哥Haskell编译器,拥有一个扩展叫作“并行列表推导式”(也叫做拉链推导式),它允许在列表推导式语法中,有多个独立分支的限定符<-。用逗号,分隔的限定符,是依赖的(“嵌套的”);而用管道符号|分隔的限定符,是并行求值的(这不涉及任何形式的多线程性,这只意味着这些分支是被拉链英语Convolution (computer science)合并的)。

-- 常规列表推导式
a = [(x,y) | x <- [1..5], y <- [6..8]]
-- [(1,6),(1,7),(1,8),(2,6),(2,7),(2,8),(3,6),(3,7),(3,8),(4,6),(4,7),(4,8),(5,6),(5,7),(5,8)]

-- 拉链列表推导式
b = [(x,y) | (x,y) <- zip [1..5] [6..8]]
-- [(1,6),(2,7),(3,6)]

-- 并行列表推导式
c = [(x,y) | x <- [1..5] | y <- [6..8]]
-- [(1,6),(2,7),(3,8)]

Python语言的语法示例:

# 常规列表推导式
>>> [(x, y) for x in range(1, 6) for y in range(6, 9)]
[(1, 6), (1, 7), (1, 8), (2, 6), (2, 7), (2, 8), (3, 6), (3, 7), (3, 8), (4, 6), (4, 7), (4, 8), (5, 6), (5, 7), (5, 8)]

# 并行/拉链列表推导式
>>> s = zip(range(1, 6), range(6, 9))
>>> t = [x for x in s]
>>> print(t)
[(1, 6), (2, 7), (3, 8)]
>>> from operator import add
>>> [*map(add, range(1, 6), range(6, 9))] # 有二个实际参数列表的map相当于Haskell的zipWith
[7, 9, 11]
>>> from itertools import starmap, zip_longest
>>> [*starmap(add, t)]
[7, 9, 11]
>>> s = zip_longest(range(1, 6), range(6, 9))
>>> t = [*s]
>>> print(t)
[(1, 6), (2, 7), (3, 8), (4, None), (5, None)]
>>> [*zip(*t)]
[(1, 2, 3, 4, 5), (6, 7, 8, None, None)]

单子推导式

Haskell中,单子推导式将列表推导式,推广为适用于任何单子[2]

集合推导式

Python语言用于生成集合的语法示例:

>>> s = {v for v in 'ABCDABCD' if v not in 'CB'}
>>> print(s)
{'A', 'D'}

字典推导式

Python语言用于生成字典(关联数组)的语法示例:

>>> s = {key: val for key, val in enumerate('ABCD') if val not in 'CB'}
>>> print(s)
{0: 'A', 3: 'D'}

类似构造

C++

C++没有直接支持列表推导的任何语言特性,但运算符重载(例如,重载|,>>,>> =)已成功用于为“嵌入式”查询领域特定语言提供表达式语法。 或者,可以使用erase–remove惯用法来构造列表推导以选择容器中的元素,并使用STL算法for_each来转换它们。

#include <algorithm>
#include <list>
#include <numeric>

using namespace std;

template<class C, class P, class T>
C comprehend(C&& source, const P& predicate, const T& transformation)
{
  // 初始化目标
  C d = forward<C>(source);

  // 元素过滤
  d.erase(remove_if(begin(d), end(d), predicate), end(d));

  // 应用变换
  for_each(begin(d), end(d), transformation);

  return d;
}

int main()
{
  list<int> range(10);  
      // range 是一个有10个元素的list, 全是0
  iota(begin(range), end(range), 1);
      // range 现在包含 1,2,...,10

  list<int> result = comprehend(
      range,
      [](int x){return x*x <= 3;},
      [](int &x){x *= 2;});
      // 结果现在包含 4,6,...,20
}

参见

延伸阅读

  • List Comprehension[3] in The Free On-line Dictionary of Computing, Editor Denis Howe.
  • Trinder, Phil. Comprehensions, a query notation for DBPLs. Proceedings of the third international workshop on Database programming languages: bulk types & persistent data, Nafplion, Greece: 55–68. 1992. 
  • Wadler, Philip. Comprehending Monads. Proceedings of the 1990 ACM Conference on LISP and Functional Programming, Nice. 1990 [2021-03-16]. (原始内容存档于2020-11-11). 
  • Wong, Limsoon. The Functional Guts of the Kleisli Query System. Proceedings of the fifth ACM SIGPLAN international conference on Functional programming. International Conference on Functional Programming: 1–10. 2000. 
Haskell
  • The Haskell 98 Report, chapter 3.11 List Comprehensions[4].
  • The Glorious Glasgow Haskell Compilation System User's Guide, chapter 7.3.4 Parallel List Comprehensions[5].
  • The Hugs 98 User's Guide, chapter 5.1.2 Parallel list comprehensions (a.k.a. zip-comprehensions)[6].
OCaml
  • OCaml Batteries Included[7].
  • Language extensions introduced in OCaml Batteries Included[8].
Python
  • The Python Tutorial, List Comprehensions[9].
  • Python Language Reference, List displays[10].
  • Python Enhancement Proposal PEP 202: List Comprehensions[11].
  • Python Language Reference, Generator expressions[12].
  • Python Enhancement Proposal PEP 289: Generator Expressions[13].
Common Lisp
  • Implementation of a Lisp comprehension macro[14] by Guy Lapalme.
Clojure
  • Clojure API documentation - for macro[15].
Axiom
  • Axiom stream examples[16].

参考文献

外部链接


Read other articles:

Ini adalah nama Korea; marganya adalah Lee. Lee Ki-wooLahir23 Oktober 1981 (umur 42)Seoul, Korea SelatanPendidikanUniversitas Dankook (B.A. dalam Administrasi Bisnis) (M.B.A. in Arts and Cultural Management)PekerjaanAktorNama KoreaHangul이기우 Hanja李己雨 Alih AksaraI Gi-uMcCune–ReischauerI Gi-u Lee Ki-woo (bahasa Korea: 이기우) (lahir 23 Oktober 1981) adalah aktor asal Korea Selatan yang dikenal karena perannya dalam A Love to Kill (2005) dan Cool Guys, Hot Ramen (2011) F...

 

Joannes Wolfius de Tabernis Montanis, Johann Wolff dari Bergzabern, 1597 Johann Wolff (lahir 10 Agustus 1537 di Bergzabern – meninggal 23 Mei 1600 di Mundelsheim) adalah seorang yuris berkebangsaan Jerman yang memiliki hubungan dengan Lelio Sozzini pada sakramen 1555. Dia juga merupakan seorang diplomat, penerjemah, sejarawan dan teolog. Dia menikah dengan Maria Magdalena Achtsynit pada 1572, kemudian istrinya tersebut meninggal pada 1581. Tahun berikutnya dia menikah dengan Christina v...

 

2009 video gameOsananajimi wa Daitouryou: My girlfriend Is the PresidentDeveloper(s)AlcotPublisher(s)JP: AlcotNA: JAST USAEngineKiriKiriPlatform(s)Microsoft WindowsReleaseJP: 30 October 2009NA: 28 December 2011Genre(s)Eroge, Visual novelMode(s)Single Player Osananajimi wa Daitouryou: My Girlfriend Is the President (幼なじみは大統領: MY GIRLFRIEND IS THE PRESIDENT Osananajimi wa Daitōryō: Mai Gārufurendo Izu za Purejidento) is a visual novel developed by Alcot and later released in ...

CDP in Montana, United StatesFrenchtown, MontanaCDPLocation of Frenchtown, MontanaCoordinates: 47°01′08″N 114°14′46″W / 47.01889°N 114.24611°W / 47.01889; -114.24611CountryUnited StatesStateMontanaCountyMissoulaArea[1] • Total6.78 sq mi (17.55 km2) • Land6.74 sq mi (17.45 km2) • Water0.04 sq mi (0.10 km2)Elevation3,045 ft (928 m)Population (2020) •...

 

Luismi QuezadaDatos personalesNombre completo Luis Miguel Quezada SánchezNacimiento Madrid, España11 de febrero de 1996 (27 años)Nacionalidad(es) EspañolaDominicanaAltura 1,71 m (5′ 7″)Peso 66 kg (145 lb)Carrera deportivaDeporte FútbolClub profesionalDebut deportivo 2015(Real Madrid C. F. C)Club Tokushima VortisLiga J2 LeaguePosición DefensaDorsal(es) 2Trayectoria Real Madrid C. F. C (2015-16) → U. E. Olot (2015-16) Real Madrid Castilla C. F. (2016-19) → Cór...

 

Mononobe no Okoshi Información personalNombre en japonés 物部尾輿 Nacimiento Siglo VIjuliano Nacionalidad JaponesaFamiliaPadre sin etiquetar Información profesionalOcupación Funcionario [editar datos en Wikidata] Mononobe no Okoshi (物部尾輿) fue un ministro japonés durante el período Kofun, y el jefe del clan Mononobe.[1]​ Según los Nihon Shoki, durante el reinado del Emperador Ankan, un collar perteneciente a Mononobe fue robado por la hija de Kikoyu Ihoki (un...

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (فبراير 2016) السنغال في الألعاب الأولمبية علم السنغال رمز ل.أ.د.  SEN ل.أ.و. اللجنة الأولمبية والرياضية الوطني...

 

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Oktober 2022. Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber:...

 

Halina Górecka Data i miejsce urodzenia 4 lutego 1938 Chorzów Wzrost 167 cm Dorobek medalowy Reprezentacja  Polska Igrzyska olimpijskie złoto Tokio 1964 lekkoatletyka(sztafeta 4 × 100 m) brąz Rzym 1960 lekkoatletyka(sztafeta 4 × 100 m) Multimedia w Wikimedia Commons Halina Sylwia Górecka z domu Richter, później (po wyjeździe z Polski) Halina Herrmann (ur. 4 lutego 1938 w Chorzowie) – polska i niemiecka lekkoatletka, mistrzyni olimp...

Iowa Highway 99Iowa 99 highlighted in redRoute informationLength33.232 mi[1] (53.482 km)Existed1931 (1931)–2003 (2003)Touristroutes Great River RoadMajor junctionsSouth end US 34 in BurlingtonNorth end US 61 in Wapello LocationCountryUnited StatesStateIowaCounties Des Moines Louisa Highway system Iowa Primary Highway System Interstate US State Secondary Scenic ← Iowa 98→ Iowa 100 Iowa Highway 99 (Iowa 99) was a state hi...

 

American romantic comedy television series With LoveGenreRomantic comedyCreated byGloria Calderón KellettStarring Emeraude Toubia Mark Indelicato Isis King Vincent Rodriguez III Rome Flynn Desmond Chiam Benito Martinez Constance Marie Todd Grinnell Music by Siddhartha Khosla Lauren Culjak Country of originUnited StatesOriginal languageEnglishNo. of seasons2No. of episodes11ProductionExecutive producers Gloria Calderón Kellett Meera Menon Andy Roth Producers Pixie Wespiser Linda Morel Sandi ...

 

Krates dari Athena, digambarkan sebagai seorang sarjana abad pertengahan di Kronik Nuremberg Krates dari Athena (Bahasa Yunani Kuno: Κράτης ὁ Ἀθηναῖος; wafat 268–264 SM)[1] merupakan seorang filsuf Platonisme dan Scholarches Akademi kuno terakhir . Krates adalah putra Antigenes dari Demos Triasia, murid dan Eromenos[2] Polemon, dan penerusnya sebagai Scholarches di Akademi Platonik,[3] pada 270–69 SM. Catatan ^ Dorandi 1999, hlm. 48. ^ ἐρ�...

У Вікіпедії є статті про інші значення цього терміна: Єгорівка. село Єгорівка Країна  Україна Область Дніпропетровська область Район Кам'янський район Громада Криничанська селищна громада Код КАТОТТГ UA12040170110038588 Облікова картка Єгорівк  Основні дані Населення 114 По...

 

List of logos used by NBC NBC Peacock redirects here. For the streaming service, see Peacock (streaming service). The first version of the modern Peacock logo, introduced on May 12, 1986. The National Broadcasting Company (NBC) has used several corporate logos over the course of its history. The first logo was used in 1926 when the radio network began operations. Its most famous logo, the peacock, was first used in 1956 to highlight the network's color programming. While it has been in use in...

 

List of EastEnders characters introduced in 1985 EastEnders' logo A photo of most of the main characters and animals who first appeared in EastEnders in 1985 The following is a list of characters that first appeared in the BBC soap opera EastEnders in 1985, by order of first appearance. They were all introduced by executive producer Julia Smith. The first episode of EastEnders was broadcast on 19 February 1985, and twenty-three main characters were already created for their first appearan...

2005 popular science book by Stephen Hawking A Briefer History of Time First editionAuthorsStephen Hawking, Leonard MlodinowCountryUnited StatesLanguageEnglishSubjectThe UniversePublished2005 (Bantam Books)Pages176 (paperback)[1]ISBN0-553-80436-7 A Briefer History of Time is a 2006 popular-science book by the English physicist Stephen Hawking and the American physicist Leonard Mlodinow. Overview The book is an update and rewrite of Hawking's 1988 A Brief History of Time. In this book ...

 

This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to additional sources.Find sources: Hisai Domain – news · newspapers · books · scholar · JSTOR (November 2021) Hisai Domain久居藩under Tokugawa shogunate Japan1669–1871CapitalHisai jin'yaArea • Coordinates34°40′34″N 136°27′40″E / 34.67611°N 13...

 

2020 soundtrack album by various artistsBad Boys for Life:The SoundtrackSoundtrack album by various artistsReleasedJanuary 17, 2020 (2020-01-17)GenreHip hopreggaetonLength30:56LabelWe the BestEpicProducerDJ Khaled (exec.)will.i.amBeat BillionaireBuju BantonDaddy YankeeDawgDinuzzoDJ DurelKeith HarrisLASTNIGHTLil' JonLloyd James, Jr.OmArrPapamitrouPlay-N-SkillzQuavoRippa on the BeatScott SummersSwedeWesten WeissBad Boys chronology Bad Boys II(2003) Bad Boys for Life:The S...

1876 Louisiana gubernatorial election ← 1872 November 7, 1876 1879 →   Nominee Francis T. Nicholls Stephen B. Packard Party Democratic Republican Popular vote 84,487 76,477 Percentage 52.49% 47.51% Governor before election William Pitt Kellogg Republican Elected Governor Francis T. Nicholls Democratic Elections in Louisiana Federal government Presidential elections 1812 1816 1820 1824 1828 1832 1836 1840 1844 1848 1852 1856 1860 1864 1868 1872 1876 1880 1884 18...

 

American family established by Frederick Douglass This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Douglass family – news · newspapers · books · scholar · JSTOR (November 2018) (Learn how and when to remove this template message) DouglassFrederick Douglass (right) with grandson Joseph Douglass (c. 1890s).Pare...

 
Kembali kehalaman sebelumnya