代码及内容源自《Fluent Python》——Luciano Ramalho 著
1 列表解析(List Comprehensions)
>>> symbols = '$£¢¥€※'
>>> codes=[]
>>> for symbol in symbols:
... codes.append(ord(symbol))
>>> codes
[36, 163, 162, 65509, 8364, 8251]
>>> codes_2=[ord(symbol) for symbol in symbols]
>>> codes_2
[36, 163, 162, 65509, 8364, 8251]
了解一点Python的人都能读懂codes这个例子,但是在熟悉列表解析之后,会发现codes_2的可读性更强,因为它的目的更加清楚。
>>> beyond_ascii=list(filter(lambda c: c>127, map(ord, symbols)))
>>> beyond_ascii
[163, 162, 65509, 8364, 8251]
>>> beyond_ascii_2=[ord(s) for s in symbols if ord(s) > 127]
>>> beyond_ascii_2
[163, 162, 65509, 8364, 8251]
列表解析可以实现map和filter函数的功能,并且不需要在此挑战lambda表达式。
>>> colors=['black', 'white']
>>> sizes=['S','M','L']
>>> tshirts=[(color, size) for color in colors for size in sizes]
>>> tshirts
[('black', 'S'),
('black', 'M'),
('black', 'L'),
('white', 'S'),
('white', 'M'),
('white', 'L')]
>>> for color in colors:
... for size in sizes:
... print((color, size))
('black', 'S')
('black', 'M')
('black', 'L')
('white', 'S')
('white', 'M')
('white', 'L')
>>> tshirts=[(color, size) for size in sizes for color in colors]
>>> tshirts
[('black', 'S'),
('white', 'S'),
('black', 'M'),
('white', 'M'),
('black', 'L'),
('white', 'L')]
列表解析也可以生成两个或多个列表的笛卡儿积(Cartesian Product),上例中,通过改变size和color语句的顺序,可以调整所生成列表的排序。
2 生成器表达式(Generator Expression)
生成器表达式与列表解析采用相同的语法,不同的是它使用“()”, 列表解析使用“[]”。
>>> tuple(ord(symbol) for symbol in symbols)
(36, 163, 162, 65509, 8364, 8251)
>>> import array
>>> array.array('I', (ord(symbol) for symbol in symbols))
array('I', [36, 163, 162, 65509, 8364, 8251])
列表解析也可以用来初始化tuples、arrays、以及其他序列,但是使用生成器表达式能够节省内存,因为它利用迭代协议一项一项地生成内容,而不是建立一个列表后提供给另一个构造器。
>>> for tshirt in ('%s %s' % (c, s) for c in colors for s in sizes):
... print(tshirt)
black S
black M
black L
white S
white M
white L
这个例子中并不会产生一个包含所有6种衬衫的列表。