首页 > 解决方案 > 如果字典为空,则字典上的 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

我不明白为什么。

标签: pythondictionaryfor-loop

解决方案


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

推荐阅读