开发者

Python Two-Dimensional Query..

I am seeing a very unusual behavior in python.. Kindly let me know what am i doing wrong!!

bc = [[0]*(n+1)]*(n+1)

for i in range(n+1):
    bc[i][i] = 1

print (bc)        

Output

[[1, 1开发者_运维百科, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]

I am trying to initialize the diagonal elements of two dimensional array to 1, but it is initializing all the elements with 1. I think I am doing something wrong with accessing two dimensional Array..

Also, kindly let me know how can I use two loops to access all the elements of two dimensional array.. my next step..

Thanks.


Your array is initialized incorrectly. The correct way to initialize a 2d array is this:

bc = [[0 for i in xrange(n + 1)] for i in xrange(n + 1)]

It's a common mistake, but the * operator copies the pointer to an list rather than copying the list, so while it looks like you have a 2d list, you actually have a 1d list of pointers to the same list.


the problem is that each array in your array is the same array in memory. you need a new array each time. the [[0]]*6 will for example make 6 of the same arrays in an array, editing one of them will update the other ones.

e.g.

>>> x=[1]
>>> y=x
>>> x.append(3)
>>> x
[1, 3]
>>> y
[1, 3]
>>> z=[x]*3
>>> x.append(6)
>>> z
[[1, 3, 4, 6], [1, 3, 4, 6], [1, 3, 4, 6]]

here is a fix by simply editing bc to be n+1 different arrays:

n=4
bc = [[0]*(n+1) for i in range(n+1)]

for i in range(n+1):
    bc[i][i] = 1

print (bc)

[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]


Try this one:

bc = [[0 for i in range(n+1)] for j in range(n+1)]

In your example you have only one (!) instance of [0] which is referenced multiple times. So if you change that instance, all references are changed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜