运行时错误:字典在迭代期间改变了大小 [英] RuntimeError: dictionary changed size during iteration

查看:49
本文介绍了运行时错误:字典在迭代期间改变了大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

import os
import collections
def make_dictionary(train_dir):
    emails=[os.path.join(train_dir,f) for f in os.listdir(train_dir)]
    all_words=[]
    for mail in emails:
        with open(mail) as m:
            for i,line in enumerate(m):
                if i==2: #Body of email is only 3rd line of text file 
                    words=line.split()
                    all_words+=words
    dictionary=collections.Counter(all_words)
    # Paste code for non-word removal here(code snippet is given below)
    list_to_remove=dictionary.keys()
    for item in list_to_remove:
        if item.isalpha()==False:
            del dictionary[item]
        elif len(item)==1:
            del dictionary[item]
    dictionary=dictionary.mostcommon[3000]
    print (dictionary)

make_dictionary('G:\Engineering\Projects\Python\Documents\enron1\ham')

我在编写此代码时收到错误RuntimeError:字典在迭代过程中改变了大小".我有只有目录中的文本文件.任何帮助将不胜感激.

I am receiving the error "RuntimeError: dictionary changed size during iteration" on writing this code. I have only text files in the directory. Any help will be appreciated.

推荐答案

看看这两个代码片段:

d = {1: 1, 2: 2}
f = [x for x in d]
del d[1]
print(f)  # [1, 2]

和:

d = {1: 1, 2: 2}
f = d.keys()
del d[1]
print(f)  # dict_keys([2])

如您所见,在第一个字典中,字典 d 和列表 f 彼此无关;字典中的更改不会反映到列表中.

As you can see, in the first one the dictionary d and the list f are not related to one another; changes in the dict are not reflected to the list.

在第二个片段中,由于我们创建列表的方式f,它保持链接到字典,因此删除字典的元素也会删除em> 从列表中删除它们.

On the second snippet, due to the way we create the list f it remains linked to the dict so deleting elements of the dict also removes them from the list.

这两种行为可能都有用,但在您的场景中,它是您想要的第一个.

Both behaviors might be somewhere helpful but in your scenario it is the first one you want.

这篇关于运行时错误:字典在迭代期间改变了大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆