How to initialize a two-dimensional array in Python?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了How to initialize a two-dimensional array in Python?相关的知识,希望对你有一定的参考价值。
【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‘]]
以上是关于How to initialize a two-dimensional array in Python?的主要内容,如果未能解决你的问题,请参考以下文章
How to directly initialize a Map/List/Set
iOS application: how to clear notifications?
How to read a scientific paper
How to relocate tablespace directory
[特征选择] DIscover Feature Engineering, How to Engineer Features and How to Get Good at It 翻译