Home >Backend Development >Python Tutorial >一些Python中的二维数组的操作方法

一些Python中的二维数组的操作方法

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-06 11:15:241593browse

需要在程序中使用二维数组,网上找到一种这样的用法:
 

#创建一个宽度为3,高度为4的数组
#[[0,0,0], 
# [0,0,0],
# [0,0,0],
# [0,0,0]]
myList = [[0] * 3] * 4

但是当操作myList[0][1] = 1时,发现整个第二列都被赋值,变成

[[0,1,0],

[0,1,0],

[0,1,0],

[0,1,0]]

为什么...一时搞不懂,后面翻阅The Python Standard Library 找到答案

list * n—>n shallow copies of list concatenated, n个list的浅拷贝的连接

例:
 

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

[[]]是一个含有一个空列表元素的列表,所以[[]]*3表示3个指向这个空列表元素的引用,修改任何

一个元素都会改变整个列表:

所以需要用另外一种方式进行创建多维数组,以免浅拷贝:
 

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

之前的二维数组创建方式为:
 

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn