Simple analysis of list derivation in python

  • 2020-04-02 13:35:23
  • OfStack

The purpose of List comprehension is to generate a List more easily.

For example, if the elements of a list variable are all Numbers, if you need to multiply the value of each element by 2 and generate another list, here is one way:


#-*-encoding:utf-8-*-
list1 = [1,2,4,5,12]
list2 = []
for item in list1:
    list2.append(item*2)
print list2

If you use list derivation, you can do this:

#-*-encoding:utf-8-*-
list1 = [1,2,4,5,12]
list2 = [item*2 for item in list1 ]
print list2

If can be used to filter out unwanted elements, such as extracting elements less than 10 in list1:

#-*-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 the elements in the two lists, you can:

#-*-encoding:utf-8-*-
list1 = [1,2,3]
list2 = [4,5,6]
list3 = [(item1,item2) for item1 in list1 for item2 in list2 ]
print list3

The official document gives an example of a more complex transpose matrix:

#-*-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:

[1, 5, 9]
[2, 6, 10]
[3, 7, 11]
[4, 8, 12]


Related articles: