这是《Python forEverybody》练习 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
繁星coding
相关分类