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 对象中的条目?
- 我如何透明地重定向一个Python导入? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
