我正在学习 Python,以便参加研究生院的编程分班测试,这实际上是我为了感受它而编写的第一个小脚本。我的背景主要是C#和PHP,但是我在测试中不能使用任何一种语言。
我的测试脚本读取以下文本文件(test_file1.txt)。偶数行包含样本大小,奇数行包含样本中每个测试的“结果”。 EOF 标记为 0。我想读入文件,输出样本大小,并对每个测试的结果求和。您将如何使用 Python 执行此任务?我觉得我试图强迫 python 像 PHP 或 C# 一样,从我的研究来看,我猜想有一些非常“Python”的方法来做这些事情。
测试文件1.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
Thanks!
使用文件作为迭代器,然后使用iterators.islice() http://docs.python.org/2/library/itertools.html#itertools.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))
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)