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 对象中的条目?
基础教程推荐
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
