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:
JavaScript
x
13
13
1
738500.0
2
683000.0
3
647000.0
4
623500.0
5
607500.0
6
7
547000
8
644000
9
702000
10
735000
11
755000
12
765000
13
I have opened both lists like this:
JavaScript
1
8
1
average = open('average2mm.txt','r')
2
average_content = average.read()
3
average.close()
4
5
difference = open('difference2mm.txt','r')
6
difference_content = difference.read()
7
difference.close()
8
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:
JavaScript
1
9
1
with open('average2mm.txt','r') as average,
2
open('difference2mm.txt','r') as difference:
3
4
for avg, diff in zip(average, difference):
5
avg, diff = avg.strip(), diff.strip()
6
if avg and diff:
7
ratio = float(avg) / float(diff)
8
print(ratio)
9
If you want to store it in a list:
JavaScript
1
10
10
1
result = []
2
with open('average2mm.txt','r') as average,
3
open('difference2mm.txt','r') as difference:
4
5
for avg, diff in zip(average, difference):
6
avg, diff = avg.strip(), diff.strip()
7
if avg and diff:
8
ratio = float(avg) / float(diff)
9
result.append(ratio)
10
If you want to write to another file, you can either iterate over result
list and write to file, or:
JavaScript
1
12
12
1
with open('average2mm.txt','r') as average,
2
open('difference2mm.txt','r') as difference,
3
open('ratio.txt', 'w') as ratiofile:
4
5
for avg, diff in zip(average, difference):
6
avg, diff = avg.strip(), diff.strip()
7
if avg and diff:
8
ratio = float(avg) / float(diff)
9
print(ratio, file=ratiofile)
10
# Or,
11
# ratiofile.write(f'{ratio}n')
12