本文介绍了如何在不调用RuntimeError的情况下通过循环删除Counter对象中的条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from collections import *
ignore = ['the','a','if','in','it','of','or']
ArtofWarCounter = Counter(ArtofWarLIST)
for word in ArtofWarCounter:
    if word in ignore:
        del ArtofWarCounter[word]

ArtofWarCounter是一个Counter对象,其中包含《孙子兵法》中的所有文字。我正在尝试从ArtofWarCounter中删除忽略中的单词。

ArtofWarCounter is a Counter object containing all the words from the Art of War. I'm trying to have words in ignore deleted from the ArtofWarCounter.

追踪:

  File "<pyshell#10>", line 1, in <module>
    for word in ArtofWarCounter:
RuntimeError: dictionary changed size during iteration


推荐答案

要使代码更改最少,请使用 list ,以便您要迭代的对象与 Counter

For minimal code changes, use list, so that the object you are iterating over is decoupled from the Counter

ignore = ['the','a','if','in','it','of','or']
ArtofWarCounter = Counter(ArtofWarLIST)
for word in list(ArtofWarCounter):
    if word in ignore:
        del ArtofWarCounter[word]

在Python2中,您可以使用 ArtofWarCounter.keys()而不是 list(ArtofWarCounter),但是如果编写如此易于验证的代码如此简单,为什么不这样做呢?

In Python2, you can use ArtofWarCounter.keys() instead of list(ArtofWarCounter), but when it is so simple to write code that is futureproofed, why not do it?

一个更好的主意是不计算要忽略的项目

It is a better idea to just not count the items you wish to ignore

ignore = {'the','a','if','in','it','of','or'}
ArtofWarCounter = Counter(x for x in ArtofWarLIST if x not in ignore)

请注意,我将 ignore 设置为 set ,这使测试 x不能被忽略效率更高

note that I made ignore into a set which makes the test x not in ignore much more efficient

这篇关于如何在不调用RuntimeError的情况下通过循环删除Counter对象中的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-13 04:21