python列表推导式
python列表推导式 特点:语言简单,速度快等优点!!!
1,取出名字长度大于3的人
>>> names=['java','scala','python','hadoop','c','c++']
>>> names
['java', 'scala', 'python', 'hadoop', 'c', 'c++']
>>> for name in names:
... if len(name) > 3:
... print (name)
...
java
scala
python
hadoop
用列表推导式:
>>> [name.upper() for name in names if len(name) > 3]
['JAVA', 'SCALA', 'PYTHON', 'HADOOP']
>>> [name for name in names if len(name) > 3]
['java', 'scala', 'python', 'hadoop']
>>>
2,求(x,y)其中x是0~5之间的偶数,y是0~5之间的奇数组成的元组列表.
>>> [(x,y) for x in range(6) if x%2==0 for y in range(6) if y%2==1]
[(0, 1), (0, 3), (0, 5), (2, 1), (2, 3), (2, 5), (4, 1), (4, 3), (4, 5)]
3,求M中3,6,9组成的列表
M =[[1,2,3],[4,5,6],[7,8,9]]
>>> M =[[1,2,3],[4,5,6],[7,8,9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [row[2] for row in M]
[3, 6, 9]
解析:
>>> for row in M:
... print(row)
...
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
4,求M中斜线159组成的列表
>>> [M[i][i] for i in range(len(M))]
[1, 5, 9]
解析:
len(M)=3 ===> range(len(M)) = 0, 1, 2 ===>i = 0, 1, 2
当 i = 0时,M[i]=[1, 2, 3] ===> M[i][i] = [1]
当 i = 1时,M[i]=[4, 5, 6] ===> M[i][i] = [5]
当 i = 2时,M[i]=[7, 8, 9] ===> M[i][i] = [9]