Python列表解析和字典解析
相比于for循环,列表解析的语法是由底层c语言实现的,它和使用for循环遍历pyobject对象相比,性能会有很大的提升。
无条件子句的列表解析式
In [2]: [2*i for i in range(4)]
Out[2]: [0, 2, 4, 6]
带条件子句的列表解析式
In [13]: [i if i%2==0 else -1 for i in range(7)]
Out[13]: [0, -1, 2, -1, 4, -1, 6]
In [14]: [i for i in range(7) if i%2==0 else -1]
File "<ipython-input-14-09b7845471ee>", line 1
[i for i in range(7) if i%2==0 else -1]
^
SyntaxError: invalid syntax
In [15]: [i for i in range(7) if i%2==0]
Out[15]: [0, 2, 4, 6]
In [18]: [i if i%2==0 for i in range(7)]
File "<ipython-input-18-49bed909dcb4>", line 1
[i if i%2==0 for i in range(7)]
^
SyntaxError: invalid syntax
注意:当条件子句在for前时必须带上else,此时else表示不符合if条件时列表元素的取值;当条件子句在for后时不能带上else。
多重循环的列表解析式
In [3]: [(i,j) for i in [1,3,5] for j in [2,4,6]]
Out[3]: [(1, 2), (1, 4), (1, 6), (3, 2), (3, 4), (3, 6), (5, 2), (5, 4), (5, 6)]
In [11]: matrix
Out[11]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [12]: [i for row in matrix for i in row]
Out[12]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
注意:多重循环是有顺序的,按照从列表前到列表后的for出现的次序执行。
字典解析
In [19]: {key:value for key,value in [(1,11),(2,22),(3,33)]}
Out[19]: {1: 11, 2: 22, 3: 33}
posted on 2019-01-12 23:30 Frank_Allen 阅读(5053) 评论(0) 编辑 收藏 举报