简体   繁体   English

在python中创建2D数组的两种方法

[英]Two ways to create 2D array in python

What is the difference between the below two ways for creating 2d array in python? 在python中创建2d数组的以下两种方式有什么区别?

def arrays(row, column):
    myList = [[None]*column for i in range(row)]

def arrays(row, column):
   myList = [[None]*column]*row

In the first case, separate pointers are used to store your sublists. 在第一种情况下,单独的指针用于存储您的子列表。

In the second instance, the same pointer is used. 在第二个实例中,使用相同的指针。 So changing the value of one will also change the others. 因此,改变一个人的价值也会改变其他人的价值。

Here's an illustrative example:- 这是一个说明性的例子: -

def arrays1(row, column):
    return [[None]*column for i in range(row)]

def arrays2(row, column):
    return [[None]*column]*row

x = arrays1(2, 2)
y = arrays2(2, 2)

x[0][0] = 1
y[0][0] = 1

print(x)  # [[1, None], [None, None]]
print(y)  # [[1, None], [1, None]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM