我有一个名为!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循环有问题,但我无法弄清楚它是什么。请帮忙。
答案 0 :(得分: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
更好的是,使用defaultdict
或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:别忘了关闭文件对象。我懒得回去自己做,但是你应该这样做。 :^)
答案 1 :(得分:0)
以下内容应该有效。关键是使用dict来跟踪数字的出现。
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