本帖最后由 hongsandao 于 2018-4-28 01:47 编辑
列表推导式在逻辑上相当于一个循环,用[]进行包裹,常见的有如下三种方式
方式一
1个 for 循环
[Python] 纯文本查看 复制代码 In [1]: a = [x for x in range(4)]
In [2]: a
Out[2]: [0, 1, 2, 3]
上述方法一相当于
[Python] 纯文本查看 复制代码 In [12]: a = []
In [13]: for x in range(4):
...: a.append(x)
...:
In [14]: a
Out[14]: [0, 1, 2, 3]
方式二
在循环过程中使用 if
[Python] 纯文本查看 复制代码 In [102]: a = [ (x,y) for x in range(1,4) for y in range(3,6) if x != y ]
In [103]: a
Out[103]: [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5)]
上述方法二相当于
[Python] 纯文本查看 复制代码 In [96]: n = []
In [97]: for x in range(1,4):
...: for y in range(3,6):
...: if x != y:
...: n.append((x,y))
In [98]: n
Out[98]: [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5)]
方式三
2个 for 循环
[Python] 纯文本查看 复制代码 In [45]: a = [(x,y) for x in range(2) for y in range(3)]
In [46]: a
Out[46]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
上述方法三相当于
[Python] 纯文本查看 复制代码 In [53]: a = []
In [54]: for x in range(2):
...: for y in range(3):
...: a.append((x,y))
In [55]: a
Out[55]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
综上所述,列表推导式的形式如下:[ 表达式 for 变量 in 序列或迭代对象]
扩展1
根据上述方式一,我们可以扩展到以下的应用例子
[Python] 纯文本查看 复制代码 In [21]: a = [' zhangsan',' lisi ','wangwu ']
In [22]: a = [f.strip() for f in a]
In [23]: a
Out[23]: ['zhangsan', 'lisi', 'wangwu']
扩展2
根据上述方式三,我们可以扩展到以下的应用例子
[Python] 纯文本查看 复制代码 In [77]: a = [[1,2,3],[4,5,6],[7,8,9]]
In [78]: [n for li in a for n in li]
Out[78]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
该方法同理也相当于
[Python] 纯文本查看 复制代码 In [71]: a = [[1,2,3],[4,5,6],[7,8,9]]
In [72]: n = []
In [73]: for li in a:
...: for num in li:
...: n.append(num)
In [74]: n
Out[74]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
扩展3
列表推导式支持文件对象迭代
[Python] 纯文本查看 复制代码 In [114]: f = open('C:/Users/Administrator/Desktop/test.txt', 'r')
In [115]: li = [line for line in f]
In [116]: li
Out[116]: ['python!']
In [117]: f.close()
扩展4
列表推导式快速生成九九乘法表
[Python] 纯文本查看 复制代码 In [124]: print('\n'.join(['\t'.join('%d*%d=%d' % (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
该方法同理也相当于
[Python] 纯文本查看 复制代码 In [123]: for x in range(1,10):
...: for y in range(1,x+1):
...: print('%d*%d=%d' % (y, x, x*y), end='\t')
...: print(end='\n')
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
|
|