Python for Everybody第9章练习2 字典循环计数错误排查
《Python for Everybody》第9章练习2计数结果错误排查
错误根因
你的代码逻辑错误出在星期值提取后的遍历步骤:
- 执行
words = line.split()后,words是按空格拆分得到的字符串列表,对样例行From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008来说,拆分结果为['From', 'stephen.marquard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008'],words[2]确实是你要的星期字符串(比如'Sat')。 - 但你后续写了
for word in words,此时words已经被赋值为单个星期字符串,Python中对字符串做for循环遍历,会逐个迭代字符串里的每个字符,最终你统计的是所有星期字符串里单个字母的出现次数,才会得到把Sat拆成S/a/t分别计数的错误结果。
修正代码
你不需要额外写循环遍历字符串,直接拿到星期值后更新字典计数即可,修正后可直接得到预期结果:
fname = input("Enter a file name: ") hand = open(fname) counts = dict() for line in hand: line = line.rstrip() if not line.startswith('From '): continue words = line.split() # 直接提取第三个位置的星期值 day = words[2] # 直接对星期值计数,不需要遍历 if day not in counts: counts[day] = 1 else: counts[day] += 1 print(counts)
如果要简化计数逻辑,也可以用字典的get()方法替代if判断,效果完全一致:
fname = input("Enter a file name: ") hand = open(fname) counts = dict() for line in hand: line = line.rstrip() if not line.startswith('From '): continue day = line.split()[2] counts[day] = counts.get(day, 0) + 1 print(counts)
运行上述代码,输入mbox-short.txt后输出为{'Fri': 20, 'Thu': 6, 'Sat': 1},和题目要求的样例输出完全匹配。
内容的提问来源于stack exchange,提问作者user19410546
相关产品推荐
相关产品推荐

