1

我有一个名为!input.txt包含多行的文件,每行是一个从 0 到 10 的随机整数。我想编写一个程序来读取文件并计算每个整数(0-10)在文件中出现的次数。例如,如果我的输入文件中有四个“0”、两个“3”和五个“7”,程序将打印出如下内容:

Number of occurrences of 0: 4
Number of occurrences of 1: 0
Number of occurrences of 2: 0
Number of occurrences of 3: 2
Number of occurrences of 4: 0
Number of occurrences of 5: 0
Number of occurrences of 6: 0
Number of occurrences of 7: 5
Number of occurrences of 8: 0
Number of occurrences of 9: 0
Number of occurrences of 10: 0

这是我的代码:

mylist = [0,1,2,3,4,5,6,7,8,9,10]
countlist = []
inFile = open("!input.txt", "r")
count = 0

for digit in mylist:
    for line in inFile:
        if digit == int(line):
            count = count + 1
    countlist.append(count)
    count = 0

#Print out the result#
for i in range(11):
    print("Number of occurrences of {0}: {1}".format(i, countlist[i]))

结果是这样的:

Number of occurrences of 0: 4
Number of occurrences of 1: 0
Number of occurrences of 2: 0
Number of occurrences of 3: 0
Number of occurrences of 4: 0
Number of occurrences of 5: 0
Number of occurrences of 6: 0
Number of occurrences of 7: 0
Number of occurrences of 8: 0
Number of occurrences of 9: 0
Number of occurrences of 10: 0

我想我的嵌套 for 循环有问题,但我无法弄清楚它是什么。请帮忙。

4

2 回答 2

3

你的循环的一个问题是你只能循环inFile 一次,因为它是一个打开的文件对象。在你第一次通读它之后,你就在文件的末尾,没有更多的行可以读了。所以变种

inFile = open("input.txt", "r").readlines()
for digit in mylist:
    count = 0
    for line in inFile:
        if digit == int(line):
            count = count + 1
    countlist.append(count)

应该管用。但是,这需要将所有行读入内存,并对每个数字进行循环。更有效的是预先分配空间并执行一次:

mylist = [0,1,2,3,4,5,6,7,8,9,10]
countlist = [0]*len(mylist)
inFile = open("input.txt", "r")
for line in inFile:
    digit = int(line)
    countlist[digit] += 1

更好的是,使用defaultdictor Counter

from collections import Counter
inFile = open("input.txt", "r")
count = Counter()
for line in inFile:
    count[int(line)] += 1

通向半魔法:

with open("input.txt") as fp:
    count = Counter(int(line) for line in fp)

PS:不要忘记关闭文件对象。我懒得回去自己做,但你应该这样做。:^)

于 2012-09-02T05:01:26.517 回答
0

以下应该工作。关键是使用 dict 来跟踪 number 的出现。

def calc(rst, x):
    rst[int(x.strip())] +=1
    return rst

with open('input.txt','r') as f:
    result = reduce(calc, f, dict(zip(range(11),[0]*11)))

for k,v in result.items(): print k,v
于 2012-09-02T09:12:35.607 回答