【问题标题】:For-loop over dictionary fails if dictionary is empty如果字典为空,则字典上的 for 循环将失败
【发布时间】:2020-02-02 19:00:56
【问题描述】:

我正在学习 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

我不明白为什么。

【问题讨论】:

  • 如果y 为空,您希望for w in y: 做什么?没有什么可以迭代的。
  • 我没有看到您打开要阅读的文件的位置。您使用 open 打开文件
  • 是的,这不是minimal reproducible example - 请编辑您的代码,以便有人可以将其粘贴到文件中并运行它无需添加任何其他内容
  • 这不是您从文件中读取的方式。请参阅realpython.com/read-write-files-python/… 上的“遍历文件中的每一行”
  • @barny - 无法弄清楚如何为我的代码制作一个最小的可重现示例,只是为了愚蠢:-(

标签: python dictionary for-loop


【解决方案1】:
for w in y:
    y[w] = y.get(w,0) + 1

我不知道你为什么添加了第一行。

如果y一开始是空的,for w in y将遍历字典零次,并且第二行永远不会执行,所以不会向字典中添加任何内容,这就是它打印{}的原因最后。

y.get(w, 0) 已经意味着:“检查w 是否在y,如果是,给我y[w],否则给我0”。

这里不需要iffor 循环。

只需将这两行改为:

 y[w] = y.get(w,0) + 1

【讨论】:

  • 感谢您的建设性回答。昨天我上床睡觉时,我想通了这一点,并且有同样的脑电波。我早上试了一下,它工作(当然)但不得不急于工作,所以我不能在这里看。如果盯着某一点太久,似乎会失明:-)
猜你喜欢
  • 2022-11-17
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多