【wrong way:】
m=[[element] * numcols] * numrows
for example:
>>> m=[['a'] *3] * 2
>>> m
[['a', 'a', 'a'], ['a', 'a', 'a']]
>>> m[1][1]
'a'
>>> m[1][1]='b'
>>> m
[['a', 'b', 'a'], ['a', 'b', 'a']]
注意:此时m[0][1] 也被修改了, because *
is copying the address
of the object (list),m[0][1]和m[1][1] reference to same object.
【right way:】
m = [[
element
for x in range(
numcols
)] for y in range(
numrows
)]
for example:
>>> m=[['a' for x in range(3)] for y in range(2)]
>>> m
[['a', 'a', 'a'], ['a', 'a', 'a']]
>>> m[1][1]
'a'
>>> m[1][1]='b'
>>> m
[['a', 'a', 'a'], ['a', 'b', 'a']]