推导式是Python语言的另一个特有特性,可以非常方便的从一个数据序列构建一个新的序列,支持列表、集合和字典的推导
1. 列表推导式
[]推导列表,()推导生成器
l = [i for i in range(10) if i % 4 == 0]
# l type is <type 'list'>, l value is [0, 4, 8]
print 'l type is ', type(l), ', l value is ', l
g = (i for i in range(10) if i % 4 == 0)
# g type is <type 'generator'> , g value is <generator object <genexpr> at 0x100847320>
print 'g type is ', type(g), ', g value is ', g
2. 集合推导式
跟列表推导式的唯一区别是[]改为{}
l = {i for i in range(10) if i % 4 == 0}
# l type is <type 'set'> , l value is set([0, 8, 4])
print 'l type is ', type(l), ', l value is ', l
3. 字典推导式
d = {i: v for i, v in enumerate(range(2, 4)) if i == 0}
# d type is <type 'dict'> , value is {0: 2}
print 'd type is ', type(d), ', value is ', d
网友评论