我开始使用python,我尝试使用一个二维列表,我开始在每个地方都用相同的变量填充。我想到了这个:
def initialize_twodlist(foo):
twod_list = []
new = []
for i in range (0, 10):
for j in range (0, 10):
new.append(foo)
twod_list.append(new)
new = []
它给出了预期的结果,但感觉像是一种变通方法。有更简单/更短/更优雅的方法吗?
另一种方法是使用字典来保存二维数组。
twoD = {}
twoD[0,0] = 0
print(twoD[0,0]) # ===> prints 0
它可以保存任何1D, 2D值,并将其初始化为0或任何其他int值,使用集合。
import collections
twoD = collections.defaultdict(int)
print(twoD[0,0]) # ==> prints 0
twoD[1,1] = 1
print(twoD[1,1]) # ==> prints 1
要在Python中初始化二维列表,使用
t = [ [0]*3 for i in range(3)]
但是不要使用[[v]*n]*n,这是一个陷阱!
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]