简体   繁体   English

在列表中查找值的索引

[英]Find indices of values in a list

I am trying to find the indices of the integers in a list. 我试图在列表中找到整数的索引。 I have a following code that works but it takes over 45 seconds. 我有以下代码可以工作,但它需要超过45秒。 Is there a faster way that I can use? 有没有更快的方式可以使用? My code looks like following: 我的代码如下所示:

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

You're unnecessarily iterating through the Node1ID list over and over again for len(output) times, each time incrementing the integer you're looking for. 对于len(output)次,你不必要地反复遍历Node1ID列表,每次递增你正在寻找的整数。 You should instead produce a dict of lists where the integer you're looking for is the index and the matching indices are in the corresponding sub-list: 您应该生成列表的dict,其中您要查找的整数是索引,匹配的索引位于相应的子列表中:

indexes = {}
for i, x in enumerate(Node1ID):
    indexes.setdefault(x, []).append(i)

so that you can look up the list of matching indices of an integer i with: 这样你就可以用以下方法查找整数i的匹配索引列表:

indexes.get(i, [])

If you don't mind using numpy: 如果你不介意使用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])

The output is interpreted as x[0] == 1 , x[1] == 1 , x[3] == 3 , x[2] == 5 输出被解释为x[0] == 1x[1] == 1x[3] == 3x[2] == 5

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

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