3.1.4 nested list Derivation
In the list derivation, the initial expression can be any expression. Contains other list derivation types.
Think about the 3*4-Dimensional Matrix Implemented by three lists with a length of 4.
>>> Matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
...]
You can use the following list expression to convert rows and columns.
>>> [[Row [I] for row in matrix] for I in range (4)]
[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]
As we can see in the previous section, the escape list can be implemented using the for statement. Therefore, the previous example is equivalent:
>>> Transposed = []
>>> For I in range (4 ):
... Transposed. append ([row [I] for row in matrix])
...
>>> Transposed
[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]
It is also equivalent:
>>> Transposed = []
>>> For I in range (4 ):
... Transposed_row = []
... For row in matrix:
... Transposed_row.append (row [I])
... Transposed. append (transposed_row)
...
>>> Transposed
[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]
In real life, you may prefer to use built-in methods to implement complex process control. The Zip () method is applicable to this example.
>>> Zip (* matrix)
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
3.2 delete statement
The Del Delete statement can quickly delete elements from the list based on the given index rather than the value. It is different from the pop () method that can return values. The Del statement can also delete data segments from the list or clear the entire list. For example:
>>> A = [-1, 1, 66.25, 333,333,123 4.5]
>>> Del a [0]
>>>
[1, 66.25, 333,333,123,]
>>> Del a [2: 4]
>>>
[1, 66.25, 1234.5]
>>> Del a [:]
>>>
[]
The Del statement can also delete the entire variable.
>>> Del
An error will occur when referencing a later. (At least until it is assigned a value again ).