错误方式:[[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
因此,使用这种方法正确地设置默认值。
绝对正确的:
跟着麦克风的双循环回复。