本文共 720 字,大约阅读时间需要 2 分钟。
定义以及初始化
>>> a = [1,2,3]>>> a[1, 2, 3]>>> 初始化一维数组>>> [0 for x in range(10)][0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> a = [[1,1],[2,2]]>>> a[[1, 1], [2, 2]]>>> myList = [[0]*3]*4[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]>>> myList[0][1] = 1>>> myList[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
发现当初始化myList[0][1]时候所有的元素中的第二个元素都改变,因为
list * n—>n shallow copies of list concatenated, n个list的浅拷贝的连接 当*3 只是对myList的第一个元素进行拷贝,全是一个相同的引用,即指向同一地址,当改变第一个元素时候,copy的其余的元素都要改变,所以第二列的元素都改变了。则二维数组的产生代码为
>>> lists = [[ 0 for col in range(3)] for row in range(5)]>>> list[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]>>> lists[0][1] = 1>>> lists[[0, 1, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
参考博文
转载地址:http://eoiqi.baihongyu.com/