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

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


当前回答

这里有一个更简单的方法:

import numpy as np
twoD = np.array([[]*m]*n)

要初始化所有带有任何'x'值的单元格,请使用:

twoD = np.array([[x]*m]*n

其他回答

用最简单的思路来创建这个。

wtod_list = []

并添加尺寸:

wtod_list = [[0 for x in xrange(10)] for x in xrange(10)]

或者如果我们想先声明大小。我们只使用:

   wtod_list = [[0 for x in xrange(10)] for x in xrange(10)]

要在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]]

在Python中初始化一个二维数组:

a = [[0 for x in range(columns)] for y in range(rows)]

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

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

绝对正确的:

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

Python中经常出现的一个模式是

bar = []
for item in some_iterable:
    bar.append(SOME EXPRESSION)

这有助于推动列表推导式的引入,它将代码片段转换为

bar = [SOME_EXPRESSION for item in some_iterable]

这样更简短,有时也更清楚。通常,您会养成识别这些循环的习惯,并经常用推导式替换循环。

您的代码遵循此模式两次

twod_list = []                                       \                      
for i in range (0, 10):                               \
    new = []                  \ can be replaced        } this too
    for j in range (0, 10):    } with a list          /
        new.append(foo)       / comprehension        /
    twod_list.append(new)                           /