码迷,mamicode.com
首页 > 编程语言 > 详细

【转】How to initialize a two-dimensional array in Python?

时间:2017-10-06 20:06:01      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:object   res   element   注意   ddr   because   pre   lang   [1]   

【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?

标签:object   res   element   注意   ddr   because   pre   lang   [1]   

原文地址:http://www.cnblogs.com/ybluo/p/7632518.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!