Python- unexpected result in a nested for loop

  Kiến thức lập trình

I am getting unexpected results from a simple python function that uses a nested for loop. csv_file_a has 28257 rows and csv_file_b has 6822 rows.

I was expecting that if I increment the counter in the inner for loop, the counter will be 28257 * 6822 but that doesn’t seem to be occurring. If I increment the counter in the outer for loop, I get 28257 (as expected) but when I increment the counter in the inner for loop, I get 6822. What could be the problem here?

def compare_data(csv_file_a, csv_file_b):
    fp_a = open(csv_file_a, mode="r", newline='')
    _sx = csv.reader(fp_a)
    fp_b = open(csv_file_b, mode="r", newline='')
    y = csv.reader(fp_b)
    counter = 0
    for _x in _sx:
        counter += 1   #I get an output of 28257 - number of rows in csv_file_a
        for _item in y:
            #counter += 1  #I get an output of 6822 - number of rows in csv_file_b
            if somecondition:
                print(something)
            else:
                print(something else)
    print(counter)
 
compare_data(csv_file_a, csv_file_b)

LEAVE A COMMENT