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

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

提交回复
热议问题