我开始使用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 = []

它给出了预期的结果,但感觉像是一种变通方法。有更简单/更短/更优雅的方法吗?


当前回答

Matrix={}
for i in range(0,3):
  for j in range(0,3):
    Matrix[i,j] = raw_input("Enter the matrix:")

其他回答

另一种方法是使用字典来保存二维数组。

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

这是我发现的教新程序员最好的方法,而且不需要使用额外的库。不过我想要更好的。

def initialize_twodlist(value):
    list=[]
    for row in range(10):
        list.append([value]*10)
    return list

我用这种方式来创建MxN矩阵,其中m = number(行)和n = number(列)。

arr = [[None]*(n) for _ in range(m)]

我经常使用这种方法初始化2维数组

N =[[int(x) for x in input().split()] for I in range(int(input())]

你可以使用列表推导式:

x = [[foo for i in range(10)] for j in range(10)]
# x is now a 10x10 array of 'foo' (which can depend on i and j if you want)