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

后端 未结 4 949
粉色の甜心
粉色の甜心 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)        
    

提交回复
热议问题