python - 如果字典为空,则字典上的 for 循环将失败
问题描述
我正在学习 Python,但遇到了一些我自己无法弄清楚的事情。
我有一个文本文件mbox-short.txt
,其中包含以下行:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Return-Path: <postmaster@collab.sakaiproject.org>
Received: from murder (mail.umich.edu [141.211.14.90])
From louis@media.berkeley.edu Fri Jan 4 18:10:48 2008
Return-Path: <postmaster@collab.sakaiproject.org>
Received: from murder (mail.umich.edu [141.211.14.97])
From zqian@umich.edu Fri Jan 4 16:10:39 2008
Return-Path: <postmaster@collab.sakaiproject.org>
Received: from murder (mail.umich.edu [141.211.14.25])
以下代码工作正常:
x = open('mbox-short.txt')
y = dict()
count = int()
for line in x: # read every line of <file>
if line.startswith('From '): # check if <line> starts with <'From '>
line1 = line.split(' ') # split <line> into separate words -> <line1>
count = count + 1 # count every <'From '> occurence
w = line1[1] # 2nd word of <line1>
if w not in y: # check if 2nd word of <line1>(=w) is already in dict <y>
y[w] = 1 # add 2nd word of <line1> as key with <value>=1
else:
y[w] += 1 # or +1 to <value>
print(y)
即使一开始y
仍然是空字典,它也可以工作。
输出:
{'stephen.marquard@uct.ac.za': 2, 'louis@media.berkeley.edu': 3, ... 'ray@media.berkeley.edu': 1}
在我正在使用的教程中,还有另一个示例,使用以下.get
方法:
word = 'brontosaurus'
d = dict()
for c in word:
d[c] = d.get(c,0) + 1
print(d)
当我尝试这样做时:
x = 'file'
y = dict()
count = int()
for line in x: # read every line of <file>
if line.startswith('From '): # check if <line> starts with <'From '>
line1 = line.split(' ') # split <line> into separate words -> <line1>
count = count + 1 # count every <'From '> occurence
w = line1[1] # 2nd word of <line1>
for w in y: # alternate + simplified form using <dict.get> method
y[w] = y.get(w,0) + 1 # check if <w> is already in dict y, if not, add it
print(y)
它失败。输出:
{}
使用调试器我可以看到for w in y:
循环没有执行。它只是跳出来y
。
我不明白为什么。
解决方案
for w in y:
y[w] = y.get(w,0) + 1
我不知道你为什么添加了第一行。
If y
is empty at the beginning, for w in y
will iterate over the dictionary zero times, and the second line will never be executed, so nothing will be added to the dictionary, which is why it prints {}
at the end.
y.get(w, 0)
already means: "check if w
is in y
, if so give me y[w]
, otherwise give me 0".
You don't need an if
and no for
loop here.
Just change these two lines to:
y[w] = y.get(w,0) + 1
推荐阅读
- javascript - 我无法遍历我得到的数据。尝试过 forEach..、for..of 和 map()
- mysql - InnoDB 引擎的 MySQL 多值插入的内部工作
- asp.net - Microsoft Identity AzureAD ASP.NET Core 仅适用于两个租户
- java - 我可以在 Spring Boot 中为我的控制器类使用一些属性文件而不是 Swagger 注释吗
- mysql - 在 MySQL 中应用外键约束时如何处理自动创建的索引?
- django - django - ValueError:依赖于没有迁移的应用程序
- linux - Gitlab 自动部署已停止工作,服务器日志中出现“找不到匹配的主机密钥类型”错误
- python - ValueError:转换 ISO 8601 时时间数据“2021-04-06T23:51:50.514Z”与格式“%Y-%m-%dT%H:%M:%SZ”不匹配
- python - colab 笔记本中的希腊字母
- javascript - Javascript,如果值插入包含在范围内,则动态颜色 HTML 输入框