Usman Ali Tahir
Usman Ali Tahir

Reputation: 11

Replacing elements between lists in python

I am currently trying to replace elements in a 2D list with elements in another list, so as to implement a game I am making in python. Here is what I have so far:

listA = [1, 3, 5]
listB = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

for a in range(len(listA)):
    alpha = (a/3) #number of rows in listB
    beta = (a/3) #number of columns in listB
    listB[alpha][beta] = 123

When I do this, I get

[[123, 123, 123], [0, 0, 0], [0, 0, 0]] 

instead of what I want given the parameters,

[[0, 123, 0], [123, 0, 123], [0, 0, 0]]

Am I doing something wrong?

Upvotes: 1

Views: 95

Answers (4)

askewchan
askewchan

Reputation: 46530

If you use numpy this is pretty easy:

import numpy as np

A = np.array([1,3,5])
B = np.zeros((3,3))

B.flat[A] = 123

print B

out:

[[   0.  123.    0.]
 [ 123.    0.  123.]
 [   0.    0.    0.]]

Note that what .flat does is return a "flattened" version of your list:

[   0.  123.    0.  123.    0.  123.    0.    0.    0.]

Upvotes: 3

Kevin
Kevin

Reputation: 76194

Instead of iterating through the indices of listA using for a in range(len(listA)):, you should iterate through the elements of listA using for a in listA:

Assuming that the indices in A translate into coordinates in B like so:

0 1 2
3 4 5
6 7 8

Then beta, AKA the column of B corresponding to a, should be calculated as a%3, rather than a/3.

listA = [1, 3, 5]
listB = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

for a in listA:
    #two slashes is integer division, not a comment, 
    #despite markup's color scheme
    alpha = a//3 
    beta = a%3
    listB[alpha][beta] = 123

print listB

Output:

[[0, 123, 0], [123, 0, 123], [0, 0, 0]]

Upvotes: 3

Abhijit
Abhijit

Reputation: 63737

>>> listA = [1, 3, 5]
>>> listB = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> listB_unwrapped = list(chain(*listB))
>>> for i in listA:
    listB_unwrapped[i] = 123


>>> listB = zip(*[iter(listB_unwrapped)]*3)
>>> listB
[(0, 123, 0), (123, 0, 123), (0, 0, 0)]
>>> 

Upvotes: 0

Samuele Mattiuzzo
Samuele Mattiuzzo

Reputation: 11048

>>> for a in range(len(listA)):
...     alpha = (listA[a]/3) #number of rows in listB
...     beta = (listA[a]%3) #number of columns in listB
...     listB[alpha][beta] = 123
... 
>>> listB
[[0, 123, 0], [123, 0, 123], [0, 0, 0]]

you must use the elements inside your listA, or it's pointles to use the indexes generated by range. Also, you should do a bit of math to properly fetch the row and column index

edit: I suggest you take a look at Kevin's answer and explanation, mine is just a quick correction of your code.

Upvotes: 1

Related Questions