Python: Can someone explain this code or give a simpler solution? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python: Can someone explain this code or give a simpler solution?

So, I found this code to calculate the average of a column of numbers in a txt file, but I don’t understand it. Can someone please break it down for me or offer a simpler solution to understand this type of code? filename = “steps.txt” with open(filename) as f: sum = 0 numlines = 0 for line in f.readlines(): n = line.split(‘ ‘)[-1] sum += float(n) numlines += 1 average = sum / numlines print(average) It’s pretty much the section under the for loop that I don’t get.

9th Nov 2019, 11:54 PM
Blair Green
Blair Green - avatar
1 Answer
+ 1
First, we need to know how file.txt content looks like. Because there is something that doesn't make sense in here, or there is a type, and this is the line I'm talking about: n = line.split(' ')[-1] f.readlines() always returns '\n' as the last character (unless it's the end of file), so and you're giving that value to n, which does not make sense. In order for me to give you a simpler version, I need to know first how it is written. Is it like this ? 13 42 525 31.4 310 242 2 51.3 414.4 13 32 462 6 142 541 624 1525
10th Nov 2019, 12:32 AM
Aymane Boukrouh
Aymane Boukrouh - avatar