Python two-dimensional array operations, python two-dimensional array operations

Source: Internet
Author: User

Python two-dimensional array operations, python two-dimensional array operations

You need to use a two-dimensional array in the program. You can find this usage on the Internet:

123456 # Create an array with a width of 3 and a height of 4#[[0,0,0], # [0,0,0],# [0,0,0],# [0,0,0]]myList = [[0] * 3] * 4

However, when myList [0] [1] = 1, the entire second column is assigned a value and becomes

[[0, 1, 0],

[0, 1],

[0, 1],

[0, 1]

Why? I don't understand it for a moment. I will refer to The Python Standard Library to find The answer later.

List * n-> nShallow copiesOf list concatenated, n listsShortest copyConnection

Example:

123456 >>> lists = [[]] * 3>>> lists[[], [], []]>>> lists[0].append(3)>>> lists[[3], [3], [3]]

[[] Is a list containing an empty list element. Therefore, [[] * 3 indicates three references pointing to this empty list element. modify any

An element changes the entire list:

Therefore, you need to create a multi-dimensional array in another way to avoid copying:

123456 >>> lists = [[] for i in range(3)]>>> lists[0].append(3)>>> lists[1].append(5)>>> lists[2].append(7)>>> lists[[3], [5], [7]]

The previous two-dimensional array creation method is as follows:

1 myList = [([0] * 3) for i in range(4)]

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.