Python multi-dimensional array code "Ultimate Edition"

Source: Internet
Author: User

If you encounter Python multi-dimensional array code in the Python initialization language to release Python multi-dimensional array related operation solutions, you will be very angry when you study the computer, you can click on our article to view it. This article involves Python multi-dimensional array initialization code to publish Python multi-dimensional array method sample code.

In Python, initialize an array of 5x3 and each item is 0. The best method is:

 
  1. multilist = [[0 for col in range(5)] for row in range(3)]  

We know that to initialize a one-dimensional array, we can do this:

 
  1. alist = [0] * 5 

Yes, can we do this when initializing a two-dimensional array:

 
  1. multi = [[0] * 5] * 3 

In fact, this is not correct, because [0] * 5 is an object in a one-dimensional array, and * 3 only copies the object reference three times. For example, modify multi [0] [0]:

 
  1. multi = [[0] * 5] * 3  
  2. multi[0][0] = 'Love China'  

The output result of print multi is:

 
  1. [['Love China', 0, 0, 0, 0], ['Love China', 0, 0, 0, 0],
     ['Love China', 0, 0, 0, 0]]  

We modified multi [0] [0], but modified our

 
  1. multi[1][0],multi[2][0]  
  2.  

Also modified. This is not the expected result. If we write it like this:

 
  1. multilist = [[0] * 5 for row in range(3)]  
  2. multilist[0][0] = 'Love China' 

Print multilist:

 
  1. multi[1][0],multi[2][0]  
  2.  

Well, no problem. However, because the * method is easy to cause confusion and causes bugs, we recommend that you use the first method, namely:

 
  1. multilist = [[0 for col in range(5)] for row in range(3)]  

The above article is the Python multi-dimensional array initialization code release python multi-dimensional array method sample code
 

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.