thanks in advance for your help! I would like to the do the following, but I am new to Python, kind of unsure what to do efficiently.
A=[[1,1],[2,3]]
.B=[0.1,0.2,0.8,0.9]
.C=[[0.2,0.2],[0.8,0.9]]
. That means, C[i,j]=B[index=A[i,j]]
.The above is a simple example. But in practice, A can be a huge array, so I would really appreciate if there is any way to do this efficiently. Thank you!
According to your post, you already almost got the answer. If you are really looking for a one line code, you can do this.
c = B[A]
c
Out[24]:
array([[0.2, 0.2],
[0.8, 0.9]])
The code above is for numpy array. On the other hand, if it is a list, list comprehension would be required.
First try planning the sequence from index of first list and the relation with the result list.
A = [[1,1],[2,3]]
B=[0.1,0.2,0.8,0.9]
C = [[B[i] for i in j] for j in A]
print(C)
Based on your comments on answer by @PAUL ANDY DE LA CRUZ YANAC, I see that you are trying to use numpy
and avoid for loop
but as far as my knowledge, you need to use a for loop
at least once.
import numpy as np
for x, y in np.ndindex(np.array(A).shape):
A[x][y] = B[A[x][y]]
Note: This approach changes the original list A
. But if you want to create a new list, look at the solution by @Paul Dlc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.