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

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


当前回答

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

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)

其他回答

from random import randint
l = []

for i in range(10):
    k=[]
    for j in range(10):
        a= randint(1,100)
        k.append(a)

    l.append(k)




print(l)
print(max(l[2]))

b = []
for i in range(10):
    a = l[i][5]
    b.append(a)

print(min(b))

通常,当你想要多维数组时,你不想要一个列表的列表,而是一个numpy数组,或者可能是一个dict。

例如,使用numpy可以执行如下操作

import numpy
a = numpy.empty((10, 10))
a.fill(foo)
row=5
col=5
[[x]*col for x in [b for b in range(row)]]

上面会给你一个5x5的2D数组

[[0, 0, 0, 0, 0],
 [1, 1, 1, 1, 1],
 [2, 2, 2, 2, 2],
 [3, 3, 3, 3, 3],
 [4, 4, 4, 4, 4]]

它使用嵌套的列表推导式。 分类如下:

[[x]*col for x in [b for b in range(row)]]

[x]*col——>被求值的最终表达式 对于——>中的x, x将是迭代器提供的值 [b for b in range(row)]]——>迭代器。

[b for b in range(row)]]这将计算为[0,1,2,3,4],因为row=5 现在化简为

[[x]*col for x in [0,1,2,3,4]]

它的值是 [[0]*5 for x in[0,1,2,3,4]]——> with x=0第一次迭代 [[1]*5 for x in[0,1,2,3,4]]——> with x=1第二次迭代 [[2]*5 for x in[0,1,2,3,4]]——> with x=2第三次迭代 [[3]*5 for x in[0,1,2,3,4]]——> with x=3第四次迭代 [[4]*5 for x in[0,1,2,3,4]]——> with x=4第五次迭代

错误方式:[[None*m]*n]

>>> m, n = map(int, raw_input().split())
5 5
>>> x[0][0] = 34
>>> x
[[34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None]]
>>> id(x[0][0])
140416461589776
>>> id(x[3][0])
140416461589776

使用这种方法,python不允许为外层列创建不同的地址空间,这将导致各种超出您预期的错误行为。

正确方法,但有例外:

y = [[0 for i in range(m)] for j in range(n)]
>>> id(y[0][0]) == id(y[1][0])
False

这是一个很好的方法,但如果您将默认值设置为None,则会有例外

>>> r = [[None for i in range(5)] for j in range(5)]
>>> r
[[None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]
>>> id(r[0][0]) == id(r[2][0])
True

因此,使用这种方法正确地设置默认值。

绝对正确的:

跟着麦克风的双循环回复。

lst=[[0]*n]*m
np.array(lst)

初始化所有矩阵m=行和n=列