[英]How to rightly locate a value at an index in nd array and save it as list in python?
I have a list called L. It has C number of elements. 我有一个名为L的列表。它具有C个元素。
I have a nd array called X. X has Boolean data (either 0 or 1). 我有一个称为X的nd数组。X具有布尔数据(0或1)。 It has dimension as (20,C).
它的尺寸为(20,C)。 There are 20 lists with each list having C number of elements
有20个列表,每个列表具有C个元素
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 . 我想在X中找到每个值为1的索引,然后在List L中的相同索引处找到该值,最后将L中的值存储在另一个nd数组中。 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 ?
您可以指导我改进此代码吗?
the last line should be: 最后一行应该是:
empylist.append(L[index[0]])
and I don't see what your tuple_to_list is needed for 而且我看不到您需要什么tuple_to_list
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. 尽管空名称已不再适用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.