【问题标题】:RuntimeError: dictionary changed size during iterationRuntimeError:字典在迭代期间改变了大小
【发布时间】:2017-07-12 15:59:59
【问题描述】:

这是我的代码:

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: dictionary changed size during iteration”。我有 只有目录中的文本文件。任何帮助将不胜感激。

【问题讨论】:

  • list_to_remove=dictionary.keys()更改为list_to_remove=[k for k in dictionary]以避免将keyslist关联dict,这样dict中所做的更改就不会反射回list
  • 谢谢。有用。 @Ev.Kounis

标签: python runtime-error


【解决方案1】:

看看这两个代码sn-ps:

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 彼此不相关; dict 中的更改不会反映到列表中。

在第二个 sn-p 中,由于我们创建列表 f 的方式,它仍然链接到 dict,因此删除 dict 的元素也会删除它们从列表中。

这两种行为可能都有帮助,但在您的场景中,这是您想要的第一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2015-03-31
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多