问题
I have a list called L. It has C number of elements.
I have a nd array called X. X has Boolean data (either 0 or 1). It has dimension as (20,C). There are 20 lists with each list having C number of elements
I want to locate each index that has value of 1 in X.Then I want the value at this same index in List L, and finally store this value from L in another nd array . I write the following code
emptylist=[]
for index,value in np.ndenumerate(X): #this index is a tuple like (0,3)
tuple_to_list=list(i)
if value == 1:
emptylist.append (L[tuple_to_list[1]]) #error
the program does not stop running. Can you guide me to improve this code ?
回答1:
the last line should be:
empylist.append(L[index[0]])
and I don't see what your tuple_to_list is needed for
A solution using only arrays would be the following:
L = list(np.random.rand(20)) # gives a List of radom values (to be compatible to the question)
La = np.array(L)
X = randint(0,5,(20,101)) # make an array having values from 0...4
emptylist = La[np.where(X==1)[0]] #gives those rows of L where rows of X contain 1
though the name empty is not appropriate anymore.
来源:https://stackoverflow.com/questions/40345872/how-to-rightly-locate-a-value-at-an-index-in-nd-array-and-save-it-as-list-in-pyt