Python学习笔记(三)——List Comprehension 和 Generator Expression

代码及内容源自《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种衬衫的列表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值