SeasonedLeo
SeasonedLeo

Reputation: 71

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. 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].

Upvotes: 3

Views: 74

Answers (2)

user2653663
user2653663

Reputation: 2948

If you don't mind using 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

Upvotes: 1

blhsing
blhsing

Reputation: 106445

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. 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:

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:

indexes.get(i, [])

Upvotes: 1

Related Questions