Home > Net >  Iterating through two list each contain more than row of data
Iterating through two list each contain more than row of data

Time:07-04

I have two lists each of size 45 rows, I would like to write a code that could access every element in list1 and compare it with every element in list2 so that it returns the matched element only...

I tried using this code:

list1 = df1['df2_matches'].tolist()
list2 = df11['df22_matches'].tolist()
result = []
for element in list1[0]:
 if element in list2[0]:
    result.append(element)

But the problem is that I do not want to change the index number each time. Instead, I would like to automatically iterate over each element

for example list1[0] is compared to list2[0] and list2enter image description here

CodePudding user response:

result = []
for i, j in zip(list1, list2):
    if list1[i] == list2[j]:
        result.append(i)

CodePudding user response:

Since you are trying to append the matched element into a 1d list, you can first flatten both your lists and do the comparison again. In this case, np.ravel will be a good choice. (I suppose you will receive multiple same elements since your data is repeating, unless you wish to have unique values only.)

array1 = np.ravel(df1['df2_matches'].tolist())
array2 = np.ravel(df11['df22_matches'].tolist())

result = [i for i in array1 for j in array2 if i == j]
  • Related