问题描述
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 中删除 ignore 中的单词.
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 not in ignore 更加高效
note that I made ignore into a set which makes the test x not in ignore much more efficient
这篇关于如何在不调用 RuntimeError 的情况下使用循环删除 Counter 对象中的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)