在列表中查找数值的索引

3

我正在尝试找到列表中整数的索引。我有以下代码可以工作,但需要超过45秒。我是否可以使用更快的方法?我的代码如下:

for i in range(0,len(output)) :
    indexes = [ii for ii,x in enumerate(Node1ID) if x == i].

展示一些输入和期望的输出。 - DeepSpace
2个回答

1
您正在不必要地重复遍历 Node1ID 列表 len(output) 次,每次增加您要查找的整数。您应该生成一个字典列表,其中您要查找的整数是索引,匹配的索引在相应的子列表中:
indexes = {}
for i, x in enumerate(Node1ID):
    indexes.setdefault(x, []).append(i)

这样你就可以用以下方式查找整数i的匹配索引列表:

indexes.get(i, [])

1
如果您不介意使用numpy的话:
# Get all the numbers to match (in this case len(output) = 10)
y = np.arange(10)

# Example array
x = [1,1,5,3,11]

y_indices, x_indices = np.where(x == y[:,None])
print(y_indices)
# array([1, 1, 3, 5])
print(x_indices)
# array([0, 1, 3, 2])

输出被解释为 x[0] == 1x[1] == 1x[3] == 3x[2] == 5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接