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

后端 未结 4 900
粉色の甜心
粉色の甜心 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:22

    How about something like this, fairly Pythonic imho:

    with open('test.txt') as fh:
        for i, line in enumerate(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'
    

提交回复
热议问题