Home > Blockchain >  Quick way to iterate through two arrays python
Quick way to iterate through two arrays python

Time:04-12

I've had multiple scenarios, where i had to find a huge array's items in another huge array. I usually solved it like this:

for i in range(0,len(arr1)):
        for k in range(0,len(arr1)):
            print(arr1[i],arr2[k])

Which works fine, but its kinda slow. Can someone help me, how to make the iteration faster?

CodePudding user response:

arr1 = [1,2,3,4,5]
arr2 = [4,5,6,7]
same_items = set(arr1).intersection(arr2)
print(same_items)
Out[5]: {4,5}

Sets hashes items so instead of O(n) look up time for any element it has O(1). Items inside need to be hashable for this to work. And if they are not, I highly suggest you find a way to make them hashable.

CodePudding user response:

If you need to handle huge arrays, you may want to use Python's numpy library, which assists you with high-efficiency manipulation methods and avoids you to use loops at all in most cases.

CodePudding user response:

if your array has duplicates and you want to keep them all:

arr1 = [1,2,3,4,5,7,5,4]
arr2 = [4,5,6,7]

res = [i for i in arr1 if i in arr2]
>>> res
'''
[4, 5, 7, 5, 4]

or using numpy:

import numpy as np

res = np.array(arr1)[np.isin(arr1, arr2)].tolist()
>>> res
'''
[4, 5, 7, 5, 4]
  • Related