python loop over unequal list row -


i have 2 tex files contain unequal number of rows , columns. want compare list 1 tex file other file, , if match list in other file, print corresponding number. e.g. files like

test1.txt       test2.txt  xcj2200, b      xcj1945, a, 0.1 xcj2345, e      xcj2200, b, 0.2 xcj2568, f      xcj2450, c, 0.3 ....            xcj2590, d, 0.4                 xcj3000, e, 0.4                 .... 

so want match col 1 , 2 of test1.txt col 1 , 2 of test2.txt. want final output

xcj2200  0.2 xcj2345  0.4 xcj2568 .... 

so far have written following code not giving answer want:

reader1=csv.reader(open('test1.txt','rb')) reader2=csv.reader(open('test2.txt','rb')) col1=[];col2=[];col1=[];col2=[];col3=[] row in reader1:    col1.append((row[0]))    col2.append((row[1])) row in reader2:    col1.append((row[0]))    col2.append((row[1]))    col3.append((row[2])) in range(len(col1)):    j in range(len(col1)):      if col1[j]==col1[i] or col2[j]==col1[i]:          print col1[i],col3[j]      else:          print col1[i] 

this code printing col 1 of test1.txt in multiple times of length of col 1 of test2.txt. know there wrong in last if , else condition.

probably 1 of easiest things read test2.txt dictionary can use lookup tuple(row[0], row[1]). using dict.get() allows specify default "":

with open('test2.txt', 'rb') f:     reader = csv.reader(f)     lookup = {(row[0], row[1]): row[2] row in reader} open('test1.txt', 'rb') f:     reader = csv.reader(f)     data = [(row[0], row[1]) row in reader] d in data:     print d[0], lookup.get(d, "") 

Comments