我有一个名为!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 循环有问题,但我无法弄清楚它是什么。请帮忙。