查找两个列表的索引
Find indexes of two lists
我有两个 numpy 列表:
x = ['A', 'A', 'C', 'A', 'V', 'A', 'B', 'A', 'A', 'A']
y = ['1', '2', '1', '1', '3', '2', '1', '1', '1', '1']
当 x
同时等于 'A'
和 y
等于 '2'
时,如何找到索引?
我希望获得索引 [1, 5]
。
我尝试使用:
np.where(x == 'A' and y == '2')
但它对我没有帮助。
您需要将列表转换为 numpy 数组才能使用向量化操作,例如 ==
和 &
:
import numpy as np
np.where((np.array(x) == "A") & (np.array(y) == "2"))
# (array([1, 5]),)
更短的版本(如果你确定 x 和 y 是 numpy 数组):
>>> np.where(np.logical_and(x == 'A', y == '2'))
(array([1, 5]),)
纯python溶液:
>>> [i for i,j in enumerate(zip(x,y)) if j==('A','2')]
[1, 5]
如果您想使用列表:
idx1 = [i for i, x in enumerate(x) if x == 'A']
idx2 = [i for i, x in enumerate(y) if x == '2']
list(set(idx1).intersection(idx2))
我有两个 numpy 列表:
x = ['A', 'A', 'C', 'A', 'V', 'A', 'B', 'A', 'A', 'A']
y = ['1', '2', '1', '1', '3', '2', '1', '1', '1', '1']
当 x
同时等于 'A'
和 y
等于 '2'
时,如何找到索引?
我希望获得索引 [1, 5]
。
我尝试使用:
np.where(x == 'A' and y == '2')
但它对我没有帮助。
您需要将列表转换为 numpy 数组才能使用向量化操作,例如 ==
和 &
:
import numpy as np
np.where((np.array(x) == "A") & (np.array(y) == "2"))
# (array([1, 5]),)
更短的版本(如果你确定 x 和 y 是 numpy 数组):
>>> np.where(np.logical_and(x == 'A', y == '2'))
(array([1, 5]),)
纯python溶液:
>>> [i for i,j in enumerate(zip(x,y)) if j==('A','2')]
[1, 5]
如果您想使用列表:
idx1 = [i for i, x in enumerate(x) if x == 'A']
idx2 = [i for i, x in enumerate(y) if x == '2']
list(set(idx1).intersection(idx2))