I\'m learning Python for a programming placement test I have to take for grad school, and this is literally the first little script I threw together to get a feel for it. My bac
Use the file as an iterator, then use iterators.islice() to get every second line:
from itertools import islice
with open("test_file1.txt", "r") as f:
for line in islice(f, 1, None, 2):
nums = [int(n) for n in line.split()]
print 'Sample size: {} Results: {}'.format(len(nums), sum(nums))
islice(f, 1, None, 2)
skips the first line (start=1
), then iterates over all lines (stop=None
) returning every second line (step=2
).
This'll work with whatever filesize you throw at it; it won't need any more memory than required by the internal iterator buffer.
Output for your test file:
Sample size: 3 Results: 46
Sample size: 5 Results: 214
Sample size: 4 Results: 86
Sample size: 2 Results: 102