[python] 列表推导式和生成器表达式

列表推导式  list comprehension 

生成器表达式  generator expression

注:除方括号的变化之外,生成器表达式还不返回列表。生成器表达式返回的是生成器对象,可用作for循环中的迭代器。

把一个字符串变成Unicode码位列表

>>> symbols = '!@#$%^&*abc'
>>> codes = [ord(symbol) for symbol in symbols]
>>> codes
[33, 64, 35, 36, 37, 94, 38, 42, 97, 98, 99]
>>>

使用原则:只用列表推导来创建新的列表,并且尽量保持简短(超过两行则考虑用for循环重写)

说明:Python会忽略代码里[]、{} 和() 中的换行,因此如果你的代码里有多行的列表、列表推导、生成器表达式、字典这一类的,可以省略不太好看的续行符\。

------------------------------------------------------

使用列表推导式计算笛卡儿积

>>> 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 先以颜色排列,再以尺码排列,相当于如下for循环嵌套

>>> for color in colors:
...     for size in sizes:
...         print((color, size))
...
('black', 'S')
('black', 'M')
('black', 'L')
('white', 'S')
('white', 'M')
('white', 'L')
>>>

------------------------------------------------------

 使用生成器表达式初始化元组

>>> symbols = '!@#$%^&*abc'
>>>
>>> tuple(ord(symbol) for symbol in symbols)
(33, 64, 35, 36, 37, 94, 38, 42, 97, 98, 99)
>>>
>>> list(ord(symbol) for symbol in symbols)
[33, 64, 35, 36, 37, 94, 38, 42, 97, 98, 99]
>>>
>>> set(ord(symbol) for symbol in symbols)
{64, 33, 97, 35, 36, 37, 38, 98, 99, 42, 94}
>>>

------------------------------------------------------

 使用生成器表达式计算笛卡儿积

>>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> ('%s %s'%(c, s) for c in colors for s in sizes)
>>> 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
>>>

参考书籍:《流畅的Python》2.2 列表推导式和生成器表达式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值