【问题标题】:How to get index of non-zero item in an array and use this index to get another value from another array or list如何获取数组中非零项的索引并使用此索引从另一个数组或列表中获取另一个值
【发布时间】:2020-09-28 06:28:32
【问题描述】:

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

例如:

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中找到non-zero项目/值的index [1, 1 for the example above]。然后,使用这个索引,在activity 中找到它的对应值。

Expected output:
chosen_act = [2, 3]

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

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

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

【问题讨论】:

  • 代码似乎不完整?染色体最佳定义是如何定义的?它似乎是一个数字,而不是一个可迭代的?
  • @mrxra 已经编辑了我的帖子,抱歉不匹配!
  • 如果你使用循环,你可以使用普通的 python 列表为什么 numpy?如果best_chr 有多个数组,那么预期的输出是什么?
  • @komatiraju032 这只是我现在正在工作的项目的一个sn-p。用于获取 best_chr 的一些变量在 numpy 中。所以我必须匹配它们以避免 best_chr = (array[1 0 1]),例如。
  • best_chr 总是有一个数组吗?

标签: python arrays python-3.x indexing typeerror


【解决方案1】:

你可以使用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)]

输出:

[2, 3]

【讨论】:

  • 谢谢!我只是有一个后续问题,例如它是一维数组,展平仍然有效吗?
  • @Acee 确实是的:)
  • 注意了!非常感谢,@Chris!
猜你喜欢
  • 2018-03-28
  • 2021-06-24
  • 2021-11-24
  • 1970-01-01
  • 2018-03-03
  • 2016-04-14
  • 2016-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多