gpt4 book ai didi

Python 嵌套 for 循环

转载 作者:行者123 更新时间:2023-11-30 23:41:09 25 4
gpt4 key购买 nike

我有一个名为 !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 循环有问题,但我不知道它是什么。请帮忙。

最佳答案

循环的一个问题是您只能循环 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

更好的是,使用 defaultdictCounter:

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:不要忘记关闭文件对象。我懒得回去自己做,但你应该这么做。 :^)

关于Python 嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12233488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com