繁体   English   中英

如何获取数组中非零项的索引并使用此索引从另一个数组或列表中获取另一个值

[英]How to get index of non-zero item in an array and use this index to get another value from another array or list

我有一个项目,其中您必须 select 数组中的非零项并获取其索引。 使用此索引,您必须在另一个数组或列表中找到其对应的值。

例如:

best_chr = [[1 1 0]] # numpy array
activity = [2, 3, 4]

代码如下所示:

chosen_act = [activity[item] for item in range(len(best_chr)) if item != 0]
print(chosen_act)

我打算做的是在best_chr [1, 1 for the example above] 中找到non-zero项/值的index 然后,使用这个索引,在activity中找到它的对应值。

Expected output:
chosen_act = [2, 3]

问题是,使用上面的代码,我收到以下错误:

TypeError: object of type 'numpy.int32' has no len()

任何帮助,将不胜感激! 谢谢!

您可以只使用zip

# best_chr.flatten since it looks like 2-d array
[i for i, j in zip(activity, best_chr.flatten()) if j]

如果需要使用索引,请使用numpy.flatnonzero

[activity[i] for i in np.flatnonzero(best_chr)]

Output:

[2, 3]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM