python生成列表方式:range(startindex,endindex,step)
eg:range(2,10,3)==>[2,5,8]
step缺省值为1,
利用range生成复杂列表
[ fun for x in range(start,end,step) if exp] :fun为要把range的参数变成的表达式,x为fun中的参数,exp为筛选条件
eg: [ x * 2 for x in range(1,10) ] ==>[2, 4, 6, 8, 10, 12, 14, 16, 18]
[ x * 2 for x in range(1,10) if x % 2 == 0] ==> [4, 8, 12, 16]
多层表达式:
[ fun for x in range(start1,end1,step1) for y in range(start2,end2,step2)]
原型为
L = []
for x in range(start1,end1,step1) :
for y in range(start2,end2,step2)
L.append(fun(x,y))
eg: [ str(x)+y for x in range(1,5) for y in ['a','b']] ==>[1a,1b,2a,2b,3a,3b,4a,4b]