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

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


当前回答

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

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

其他回答

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

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

要在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]]
twod_list = [[foo for _ in range(m)] for _ in range(n)]

n是行数,m是列数,foo是值。

代码:

num_rows, num_cols = 4, 2
initial_val = 0
matrix = [[initial_val] * num_cols for _ in range(num_rows)]
print(matrix) 
# [[0, 0], [0, 0], [0, 0], [0, 0]]

Initial_val必须是不可变的。

添加维度的一般模式可以从这个系列中得出:

x = 0
mat1 = []
for i in range(3):
    mat1.append(x)
    x+=1
print(mat1)


x=0
mat2 = []
for i in range(3):
    tmp = []
    for j in range(4):
        tmp.append(x)
        x+=1
    mat2.append(tmp)

print(mat2)


x=0
mat3 = []
for i in range(3):
    tmp = []
    for j in range(4):
        tmp2 = []
        for k in range(5):
            tmp2.append(x)
            x+=1
        tmp.append(tmp2)
    mat3.append(tmp)

print(mat3)