Home > Enterprise >  how to index the output of 2 arrays in nested loop
how to index the output of 2 arrays in nested loop

Time:12-20

I am writing a code in python that takes two csv files and appends them in two different arrays. and then compares each of their elements.

It is successful and prints if it exist. But how do I print the element it self that exist in the two files?

Array1=[]
Array2=[]

#opening file1
with open('Test1.csv', newline='') as csvfile:
    #reading the file
      reader = csv.reader(csvfile) 
      for row in reader:
          Array1.append(row)

#opening file2
with open('Test2.csv', newline='') as csvfile:
    #reading the file2
      reader2 = csv.reader(csvfile) 
      for row in reader2:
          Array2.append(row)          

#check if element exist
for i in Array1:
    for j in Array2:
        if i==j:
          print("exist") ```` 


I want to print the value of i==j 

CodePudding user response:

You can print variables as well

print(i, "exists")

Or use fstrings

print(f"{j} exists in both files")

CodePudding user response:

you can directly print i or j if condition is true.

#check if element exist
for i in Array1:
    for j in Array2:
        if i==j:
          print("exist")
          print(i)

CodePudding user response:

For better performance you can break after your print("exist"). To find intersections you can use sets (set1.intersection(set2)) for better performance, if your task is only to find intersection. For cleaner code I would recommend you to use pandas.

import csv
import pandas as pd

df1 = pd.read_csv("Test1.csv")
df2 = pd.read_csv("Test1.csv")

df_intersection = pd.merge(df1, df2)

for row in df_intersection.values.tolist():
    print(row)
    print("exist")
  • Related