Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当for循环嵌套在for循环中时,为什么天数的计数会发生变化?_Python_List_Dictionary_For Loop - Fatal编程技术网

Python 当for循环嵌套在for循环中时,为什么天数的计数会发生变化?

Python 当for循环嵌套在for循环中时,为什么天数的计数会发生变化?,python,list,dictionary,for-loop,Python,List,Dictionary,For Loop,对于每个人来说,这都是Python的问题,练习9.2 我的问题是,当for循环嵌套在for循环中时,为什么天数的计数会发生变化 这是我提供正确答案的代码:{'Sat':1,'Fri':20,'Thu':6} file_name = input("Enter a file name: ") file_handle = open(file_name) day_count_list = [] day_count_dict = dict() for line in file_

对于每个人来说,这都是Python的问题,练习9.2

我的问题是,当for循环嵌套在for循环中时,为什么天数的计数会发生变化

这是我提供正确答案的代码:
{'Sat':1,'Fri':20,'Thu':6}

file_name = input("Enter a file name: ")

file_handle = open(file_name)

day_count_list = []

day_count_dict = dict()

for line in file_handle:
    line = line.strip()
    if line.startswith("From "):
        line = line.split()
        day_counts = line[2]
        day_count_list.append(day_counts)
        
for day in day_count_list:
    day_count_dict[day] = day_count_dict.get(day, 0) + 1

print(day_count_dict)
但是,当for循环嵌套时,答案变成:
{'Sat':27,'Fri':330,'Thu':21}

for line in file_handle:
    line = line.strip()
    if line.startswith("From "):
        line = line.split()
        day_counts = line[2]
        day_count_list.append(day_counts)
        for day in day_count_list:
            day_count_dict[day] = day_count_dict.get(day, 0) + 1

在第二个代码中,对于外部循环的每次迭代,内部
for
循环将一直运行。这意味着内部循环的主体将运行多次


这与第一个代码的行为不同,第一个循环运行一次后,第二个for循环将运行一次。

使用调试器逐步完成执行,并查看每一行如何更改程序的状态。要获得更好的答案,请在问题中包含程序正在阅读的文件。到目前为止,我们还不知道它的计数是多少,因为在外循环的每个后续迭代中,都会从外循环的第一次迭代中再加上一个Sat。如果您想要嵌套循环,您应该为外部循环的每个迭代清除day\u count\u列表