0

我正在学习 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

谢谢!

4

4 回答 4

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))

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
于 2013-04-15T19:01:22.327 回答
4

你可以这样做:

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)
于 2013-04-15T18:59:14.637 回答
2

像这样的东西怎么样,相当Pythonic恕我直言:

with open('test.txt') as fh:
    for i, line in enumerate(fh):
        if i % 2:
            nums = map(int, line.split())
            print 'Sample size: %d, Results: %d' % (len(nums), sum(nums))
        elif line == '0':
            print 'End of experiment'
于 2013-04-15T19:05:52.113 回答
0

我不确定 pythonic 的人如何找到这个,但我发现 zip、ma​​p 和 reduce 是一种非常方便的方式,可以以紧凑的方式完成此操作。但是,它可能有点混淆。

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)        
于 2013-04-15T19:42:02.857 回答