列表解析来自函数式编程语言(haskell),语法如下:
[expr for iter_var in iterable]
[expr for iter_var in iterable if cond_expr]
第一种语法:首先迭代iterable里所有内容,每一次迭代,都把iterable里相应内容放到iter_var中,再在表达式中应用该iter_var的内容,最后用表达式的计算值生成一个列表。(iterable为可迭代对象,对此不了解请看本站文章python生成器与迭代器)的内容。
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lists = [x*x for x in range(10)]
>>> lists
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> type(lists)
<type 'list'>
>>>
第二种语法:加入了判断语句,只有满足条件的内容才把iterable里相应内容放到iter_var中,再在表达式中应用该iter_var的内容,最后用表达式的计算值生成一个列表。
>>> lists = [x for x in range(10) if x%2==0]
>>> lists
[0, 2, 4, 6, 8]
>>>
用map,filter,lambda函数可达到第二种语法的例子同样的效果
>>> lists = map((lambda x:x),filter((lambda x:x%2==0),range(10)))
>>> lists
[0, 2, 4, 6, 8]
>>>
举例说明一:
>>> num = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> num
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 10, 15, 20, 25, 30, 35, 40, 45, 12, 18, 24, 30, 36, 42, 48, 14, 21, 28, 35, 42, 49]
举例说明二:
>>> sentence = 'Life is too short I use the python'
>>> sentencelist = sentence.split()
>>> sentencelist
['Life', 'is', 'too', 'short', 'I', 'use', 'the', 'python']
>>> stuff = [[x.upper(), x.lower(), len(x)] for x in sentencelist]
>>> for i in stuff:
print i
['LIFE', 'life', 4]
['IS', 'is', 2]
['TOO', 'too', 3]
['SHORT', 'short', 5]
['I', 'i', 1]
['USE', 'use', 3]
['THE', 'the', 3]
['PYTHON', 'python', 6]
>>>
举例二的map,lambda实现
>>> sentence = 'Life is too short I use the python'
>>> sentencelist = sentence.split()
>>> sentencelist
['Life', 'is', 'too', 'short', 'I', 'use', 'the', 'python']
>>> stuff = map(lambda x:[x.upper(), x.lower(), len(x)],sentencelist)
>>> for i in stuff:
print i
['LIFE', 'life', 4]
['IS', 'is', 2]
['TOO', 'too', 3]
['SHORT', 'short', 5]
['I', 'i', 1]
['USE', 'use', 3]
['THE', 'the', 3]
['PYTHON', 'python', 6]
>>>
示例三: 一行代码,打印九九乘法表
>>> print '\n'.join([' '.join(['%s*%s=%-2s' % (y,x,x*y) for y in range(1,x+1)]) for x in range(1,10)])
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
>>>