我正在学习 Python 以进行研究生院的编程分班考试,这实际上是我拼凑起来的第一个小脚本来感受它。我的背景主要是 C# 和 PHP,但我不能在测试中使用任何一种语言。
我的测试脚本读入以下文本文件 (test_file1.txt)。偶数行包含样本大小,奇数行包含样本中每个测试的“结果”。EOF 标记为 0。我想读入文件,输出样本量,并对每个测试的结果求和。您将如何使用 Python 执行此任务?我觉得我试图强迫 python 像 PHP 或 C# 一样,根据我的研究,我猜想有非常“Python”的方式来做这些事情。
test_file1.txt:
3
13 15 18
5
19 52 87 55 1
4
11 8 63 4
2
99 3
0
我的简单脚本:
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()
我的结果:
Sample size: 3 Results: 46
Sample size: 5 Results: 214
Sample size: 4 Results: 86
Sample size: 2 Results: 102
End of experiment
谢谢!