使用 Python 以数组索引表示的列表元素

社会演员多 python 434

原文标题Elements of list in terms of array indices using Python

如何根据A的数组索引编写列表B的元素?附加了所需的输出。

import numpy as np
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
B = [1,5,6]

所需的输出是

B=[A[0,0], A[1,1], A[1,2]]

原文链接:https://stackoverflow.com//questions/71463422/elements-of-list-in-terms-of-array-indices-using-python

回复

我来回复
  • enke的头像
    enke 评论

    可以用numpy.isin查看B中的元素是否存在于A中;然后使用numpy.where查找存在的元素的索引。由于索引是由轴分隔的,因此您最终可以解包并zip它们以获得所需的结果:

    out = list(zip(*np.where(np.isin(A, B))))
    

    对于A=np.array([[1,2,3],[4,5,6],[7,8,9]])B=[1,5,6,7],输出:

    [(0, 0), (1, 1), (1, 2), (2, 0)]
    
    2年前 0条评论