Python3.2 tutorials-nested list derivation and del keywords

Source: Internet
Author: User

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 ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.