用于对文件中所有奇数行求和的Pythonic方法

use*_*963 0 python python-2.7

我正在学习Python进行编程安置测试我必须参加研究生学习,这实际上是我为了感受它而一起投入的第一个小脚本.我的背景主要是C#和PHP,但我不能在测试中使用任何一种语言.

我的测试脚本读入下面的文本文件(test_file1.txt).偶数行包含样本大小,奇数行包含样本中每个测试的"结果".EOF标记为0.我想在文件中读取,输出样本大小,并对每个测试的结果求和.你会如何使用Python执行此任务?我觉得我试图强迫python像PHP或C#,从我的研究中我想有非常"Python"的方式做thigs.

test_file1.txt:

3
13 15 18
5 
19 52 87 55 1
4
11 8 63 4
2
99 3
0
Run Code Online (Sandbox Code Playgroud)

我的简单脚本:

file = open("test_file1.txt", "r")

i=0
for line in file:
    if i % 2 == 0:
        #num is even
        if line == '0':
            #EOF
            print 'End of experiment'   
    else:
        #num is odd
        numList = line.split( )
        numList = [int(x) for x in numList]
        print 'Sample size: ' + str(len(numList)) + ' Results: ' + str(sum(numList))
    i += 1

file.close()
Run Code Online (Sandbox Code Playgroud)

我的结果:

Sample size: 3 Results: 46
Sample size: 5 Results: 214
Sample size: 4 Results: 86
Sample size: 2 Results: 102
End of experiment
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mar*_*ers 8

使用该文件作为迭代器,然后使用iterators.islice()获取每隔一行:

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))
Run Code Online (Sandbox Code Playgroud)

islice(f, 1, None, 2)跳过第一行(start=1),然后迭代所有行(stop=None)返回每隔一行(step=2).

这适用于你抛出的任何文件大小; 它不需要内部迭代器缓冲区所需的内存.

测试文件的输出:

Sample size: 3  Results: 46
Sample size: 5  Results: 214
Sample size: 4  Results: 86
Sample size: 2  Results: 102
Run Code Online (Sandbox Code Playgroud)