Skip to content
Advertisement

Dividing each corresponding element of two lists in Python

I have two lists in seperate text files and I need to divide each value by the corresponding value in the other list. The following is a smaal bit of the data from both files:

738500.0
683000.0
647000.0
623500.0
607500.0

547000
644000
702000
735000
755000
765000

I have opened both lists like this:

average = open('average2mm.txt','r')
average_content = average.read()
average.close()

difference = open('difference2mm.txt','r')
difference_content = difference.read()
difference.close()

I presume I have to use the proper loop to divide both lists but I haven’t managed to get it done yet.

Advertisement

Answer

A readable, clean and safe way of doing this would be:

with open('average2mm.txt','r') as average, 
     open('difference2mm.txt','r') as difference:

    for avg, diff in zip(average, difference):
        avg, diff = avg.strip(), diff.strip()
        if avg and diff:
            ratio = float(avg) / float(diff)
            print(ratio)

If you want to store it in a list:

result = []
with open('average2mm.txt','r') as average, 
     open('difference2mm.txt','r') as difference:

    for avg, diff in zip(average, difference):
        avg, diff = avg.strip(), diff.strip()
        if avg and diff:
            ratio = float(avg) / float(diff)
            result.append(ratio)

If you want to write to another file, you can either iterate over result list and write to file, or:

with open('average2mm.txt','r') as average, 
     open('difference2mm.txt','r') as difference, 
     open('ratio.txt', 'w') as ratiofile:

    for avg, diff in zip(average, difference):
        avg, diff = avg.strip(), diff.strip()
        if avg and diff:
            ratio = float(avg) / float(diff)
            print(ratio, file=ratiofile)
            # Or,
            # ratiofile.write(f'{ratio}n')
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement