Python list comprehension features: simple language, fast speed and other advantages! ! !
1. Take out people whose name length is greater than 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
Use list comprehensions:
>>> [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. Find (x, y) where x is an even number between 0 and 5 and y is a list of tuples consisting of odd numbers between 0 and 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. Find the list of 3, 6, 9 in M
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]
Parse:
>>> for row in M:
... print(row)
...
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
4. Find the list of slashes 159 in M
>>> [M[i][i] for i in range(len(M))]
[1, 5, 9]
Parse:
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]