0.目录

1.遇到的问题

2.创建二维数组的办法

•3.1 直接创建法

•3.2 列表生成式法

•3.3 使用模块numpy创建

1.遇到的问题

m = n = 3
test = [[0] * m] * n
print("test =", test)

test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

m = n = 3
test = [[0] * m] * n
print("test =", test)

test[0][0] = 233
print("test =", test)

test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
test = [[233, 0, 0], [233, 0, 0], [233, 0, 0]]

Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:

>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:
>>>
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]

2.创建二维数组的办法

2.1 直接创建法

test = [0, 0, 0], [0, 0, 0], [0, 0, 0]]

2.2 列表生成式法

test = [[0 for i in range(m)] for j in range(n)]

2.3 使用模块numpy创建

import numpy as np
test = np.zeros((m, n), dtype=np.int)

tags: gt,lists,list,numpy,创建,Python,zeros,append,生成式,二维,数组

1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责；
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性，不作出任何保证或承若；
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。