8.2 列表解析

列表解析(list comprehension,简称listcomp)让你可以通过声明在单行内构造列表的内容。

没有列表解析的情况

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

>>> x = []
>>> for i in (1, 2, 3):
...   x.append(i)
...
>>> x
[1, 2, 3]

使用列表解析的实现

>>> x = [i for i in (1, 2, 3)]
>>> x
[1, 2, 3]

可以同时使用多条for语句并使用if语句过滤元素:

x = [word.capitalize()
   for line in ("hello world?", "world!", "or not")
   for word in line.split()
   if not word.startswith("or")]
>>> x
['Hello', 'World?', 'World!', 'Not']

使用列表解析而不使用循环是快速定义列表的简洁方式。因为我们仍然在讨论函数式编程,值得一提的是通过列表解析构建的列表是不能依赖于程序的状态的1。这通常让它们比非列表解析构建的列表更加简洁易读。

 注意

也有一些语法用于以同样的方式构建字典和集合:
> {x:x.upper() for x in ['hello', 'world']}
{'world': 'WORLD', 'hello': 'HELLO'}
> {x.upper() for x in ['hello', 'world']}
set(['WORLD', 'HELLO'])
注意,这只在Python 2.7及后续版本中有效。