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

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

    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.

    with open("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 in zip(lines, lines[1:], range(len(lines)))                                                                  
                       if d[2] % 2 == 0)        
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2021-01-27 08:30

    You could do:

    with open("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)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题