複数の行を含むというファイルがあります!input.txt
。各行は0から10までのランダムな整数です。ファイルを読み取り、各整数(0-10)がファイルに現れる回数を計算するプログラムを作成します。たとえば、入力ファイルに4つの「0」、2つの「3」、5つの「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ループに何か問題があると思いますが、それが何であるかを理解できませんでした。助けてください。