Python multi-dimensional array method example code initialize an array of 5x3 and each item is 0 in Python. the best method is:
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:
Alist = [0] * 5
Yes, can we do this when initializing a two-dimensional array:
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]:
Multi = [[0] * 5 ] * 3
Multi [0] [0] = ' Love China '
Print MultiThe output result is:
[['Love China', 0, 0, 0, 0], ['Love China', 0, 0, 0], ['Love China', 0, 0, 0, 0]
We modified multi [0] [0], but modified our multi [1] [0] and multi [2] [0. This is not the expected result.
If we write it like this:
Multilist = [[0] * 5 For Row In Range ( 3 )]
Multilist [0] [0] = ' Love China '
Print MultilistThe output result is as follows:
[['Love China', 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]
Well, no problem. However, because the * method is easy to cause confusion and causes bugs, we recommend that you use the first method, namely:
Multilist = [[0 For Col In Range ( 5 )] For Row In Range ( 3 )]
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.