List comprehension is to generate lists more conveniently.
For example, the elements of a list variable are numbers. If you need to multiply the value of each element by 2 and generate another list, the following is a way to do it:
Copy the codeThe code is as follows:
#-*-encoding:utf-8-*-
list1 = [1,2,4,5,12]
list2 = []
for item in list1:
(item*2)
print list2
If using list comprehension, you can do this:
Copy the codeThe code is as follows:
#-*-encoding:utf-8-*-
list1 = [1,2,4,5,12]
list2 = [item*2 for item in list1 ]
print list2
You can filter out unwanted elements through if, for example, extract elements less than 10 in list1:
Copy the codeThe code is as follows:
#-*-encoding:utf-8-*-
list1 = [1,2,4,5,12]
list2 = [item for item in list1 if item < 10 ]
print list2
If you want to combine elements from two lists, you can:
Copy the codeThe code is as follows:
#-*-encoding:utf-8-*-
list1 = [1,2,3]
list2 = [4,5,6]
list3 = [(item1,item2) for item1 in list1 for item2 in list2 ]
print list3
An example of a relatively complex transpose matrix is given in the official documentation:
Copy the codeThe code is as follows:
#-*-encoding:utf-8-*-
matrix1 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
matrix2 = [[row[i] for row in matrix1] for i in range(4)]
for row in matrix2:
print row
The operation results are as follows:
Copy the codeThe code is as follows:
[1, 5, 9]
[2, 6, 10]
[3, 7, 11]
[4, 8, 12]