array1 = [[1, 2, 3], [4, 5, 6], [2, 5, 8], [5, 6, 9] ]
array2 = [[1, 2, 3], [2, 5, 8]]
array2 has a similar column in array1 at index 0 and 2 I want index as output that is 0 and 2
Is it possible to solve without using any long for loop in python?
CodePudding user response:
You can use numpy
and use all
and any
like below:
>>> import numpy as np
>>> array1 = np.array(array1)
>>> array2 = np.array(array2)
>>> res = (array1 == array2[:,None]).all(-1).any(0)
>>> res
array([ True, False, True, False])
>>> idx, = np.nonzero(res)
>>> idx
array([0, 2])
CodePudding user response:
It can't be done without some sort of open or hidden iteration. Some approach with a set and a comprehension:
s2 = set(map(tuple, array2))
indices = [i for i, t in enumerate(map(tuple, array1)) if t in s2]
CodePudding user response:
You can also use a list comprehension.
array1 = [[1, 2, 3], [4, 5, 6], [2, 5, 8], [5, 6, 9] ]
array2 = [[1, 2, 3], [2, 5, 8]]
output = [i for i in range(len(array1)) if array1[i] in array2]
#[0, 2]
CodePudding user response:
You could create a dictionary. This avoids quadratic behavior:
array1 = [[1, 2, 3], [4, 5, 6], [2, 5, 8], [5, 6, 9] ]
array2 = [[1, 2, 3], [2, 5, 8]]
d = {tuple(column):i for i,column in enumerate(array1)}
duplicates = [d[tuple(column)] for column in array2 if tuple(column) in d]
print(duplicates) #[0,2]
CodePudding user response:
you can just use:
array1 = [[1, 2, 3], [4, 5, 6], [2, 5, 8], [5, 6, 9] ]
array2 = [[1, 2, 3], [2, 5, 8]]
res = [array1.index(elem) for elem in array1 if elem in array2]
# [0, 2]
what is equivalent of:
res = []
for elem in array1:
if elem in array2:
res.append(array1.index(elem))
print (res)
# [0, 2]