Posted via CodeCall Mobile
im trying to use a 2d array in my program, and i cant seem to find where im going wrong.
what i wanted was to assign the first rows first box with 0, not all of them.Code:box=[0]*3 box2=[box]*3 box[0][0]=1 box[0][0] >>>[[1,0,0],[1,0,0],[1,0,0]]
any help?
This is since all of your three arrays are actually the same one. Therefor when you change the first one all three are changed.
Edit: Sorry I forgot to tell how to solve it. Do something like this to actually copy it:
I'm at school now so I can't test it but I think that will work.Code:box=[0]*3 box=copy.deepcopy(box)*3 box[0][0]=1
Posted via CodeCall Mobile
thanks.i.ll try it when i can get on. Ty!
Posted via CodeCall Mobile
ok, tested it, same results. Have to import copy btw. Thx tho.![]()
Ok, I will test it when I comes home.
Posted via CodeCall Mobile
on a side note: ive never used deepcopy before, and i actually needed it in anotha part of the program. So thanks for the tip.![]()
Posted via CodeCall Mobile
well ive done what i can for tonite, and i wont have time to get on tomoz. So thanks, and i.ll try again later.
I solved the problem now. The problem before was that we made a copy and then added that three times instead of creating three copies. Here's the solution:
Code:import copy base=[0]*3 box=[] for i in range(0,3): box+=copy.deepcopy([base]) box[0][0] = 1 print box
Posted via CodeCall Mobile
ahhhhh. Thanks. Much appreciated.![]()
same thing using the whole power of Python:
Code:>>> [[int(i==0) for i in range(3)] for j in range(3)] [[1, 0, 0], [1, 0, 0], [1, 0, 0]] #with x=4 and y=5 >>> [[int(i==0) for i in range(x)] for j in range(y)] [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]![]()
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks