Pythonic Method To Sum All The Odd-numbered Lines In A File
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 backgro
Solution 1:
Use the file as an iterator, then use iterators.islice()
to get every second line:
from itertools import islice
withopen("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:46Sample size: 5 Results:214Sample size: 4 Results:86Sample size: 2 Results:102
Solution 2:
You could do:
withopen("test_file1.txt", "r") as inf:
lines = inf.readlines()
for l in lines[1::2]: # read only alternating lines
numList = map(int, line.split())
print"Sample size:", len(numList), "Results:", sum(numList)
Solution 3:
How about something like this, fairly Pythonic imho:
withopen('test.txt') as fh:
for i, line inenumerate(fh):
if i % 2:
nums = map(int, line.split())
print'Sample size: %d, Results: %d' % (len(nums), sum(nums))
elif line == '0':
print'End of experiment'
Solution 4:
I'm not sure how pythonic people may find this, but I find that zip, map, and reduce to be a pretty handy way to do this in a compact way. However, it can be a bit obfuscated.
withopen("test.txt") as fd:
lines = [map(int, s.strip().split()) for s in fd.readlines()]
print"\n".join("Sample Size: %d \t Results: %d"%tuple(map(sum,(d[0],d[1])))
for d inzip(lines, lines[1:], range(len(lines)))
if d[2] % 2 == 0)
Post a Comment for "Pythonic Method To Sum All The Odd-numbered Lines In A File"