How do I remove entries within a Counter object with a loop without invoking a RuntimeError?(如何在不调用 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 中删除 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 对象中的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不调用 RuntimeError 的情况下使用循环删除 Counter 对象中的条目?


基础教程推荐
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01