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

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


当前回答

如果它是一个稀疏填充的数组,你可能最好使用一个以元组为键的字典:

dict = {}
key = (a,b)
dict[key] = value
...

其他回答

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

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

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

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

绝对正确的:

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

要初始化一个2维数组,使用: Arr = [[]*m for I in range(n)]

实际上, arr = [[]*m]*n将创建一个2D数组,其中所有n个数组都指向同一个数组,因此任何元素的任何值变化都将反映在所有n个列表中

更多详细解释请访问:https://www.geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way/

如果它是一个稀疏填充的数组,你可能最好使用一个以元组为键的字典:

dict = {}
key = (a,b)
dict[key] = value
...
t = [ [0]*10 for i in [0]*10]

对于每个元素将创建一个新的[0]*10。