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

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


当前回答

如果你使用numpy,你可以很容易地创建2d数组:

import numpy as np

row = 3
col = 5
num = 10
x = np.full((row, col), num)

x

array([[10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10]])

其他回答

这种方式比嵌套的列表推导更快

[x[:] for x in [[foo] * 10] * 10]    # for immutable foo!

下面是一些python3计时,用于小型和大型列表

$python3 -m timeit '[x[:] for x in [[1] * 10] * 10]'
1000000 loops, best of 3: 1.55 usec per loop

$ python3 -m timeit '[[1 for i in range(10)] for j in range(10)]'
100000 loops, best of 3: 6.44 usec per loop

$ python3 -m timeit '[x[:] for x in [[1] * 1000] * 1000]'
100 loops, best of 3: 5.5 msec per loop

$ python3 -m timeit '[[1 for i in range(1000)] for j in range(1000)]'
10 loops, best of 3: 27 msec per loop

解释:

[[foo]*10]*10创建重复10次的相同对象的列表。您不能只使用这个,因为修改一个元素将修改每行中的同一元素!

x[:]等价于list(x),但更有效一点,因为它避免了名称查找。无论哪种方式,它都创建了每行的浅拷贝,所以现在所有元素都是独立的。

所有的元素都是相同的foo对象,所以如果foo是可变的,你就不能使用这个方案。,你必须使用

import copy
[[copy.deepcopy(foo) for x in range(10)] for y in range(10)]

或者假设一个类(或函数)Foo返回Foo

[[Foo() for x in range(10)] for y in range(10)]

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

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

初始化一个大小为m X n的二维矩阵,取值为0

m,n = map(int,input().split())
l = [[0 for i in range(m)] for j in range(n)]
print(l)

错误方式:[[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

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

绝对正确的:

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

对于那些困惑为什么[["]*m]*n不好用的人。

最好的方法是[[" for i in range(columns)] for j in range(rows)] 这将解决所有问题。

如需进一步澄清 例子:

>>> x = [['']*3]*3
[['', '', ''], ['', '', ''], ['', '', '']]
>>> x[0][0] = 1
>>> print(x)
[[1, '', ''], [1, '', ''], [1, '', '']]
>>> y = [['' for i in range(3)] for j in range(3)]
[['', '', ''], ['', '', ''], ['', '', '']]
>>> y[0][0]=1
>>> print(y)
[[1, '', ''], ['', '', ''], ['', '', '']]