Pythonic method to sum all the odd-numbered lines in a file

后端 未结 4 945
粉色の甜心
粉色の甜心 2021-01-27 07:38

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

4条回答
  •  無奈伤痛
    2021-01-27 08:35

    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
    

提交回复
热议问题