从python集合中删除多个条目

2024-04-26 22:38:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从我的集合计数器中删除多个条目,但是我得到了一个TypeError

sentence="Hello 123 Bye 456"
letters = collections.Counter(sentence)
ignore=[' ','1','2','3','4','5','6','7','8','9']
if ignore in letters:
    del letters[ignore]

但我有个错误:

TypeError: unhashable type: 'list'

已经看过How to remove an item from a "collections.defaultdict"?


Tags: inhelloif错误counter计数器条目collections
1条回答
网友
1楼 · 发布于 2024-04-26 22:38:35

与创建整个计数并删除不需要的内容相比,最好首先只计算您需要的内容:

import collections

sentence = "Hello 123 Bye 456"
ignore = [' ','1','2','3','4','5','6','7','8','9']

letters = collections.Counter(x for x in sentence if x not in ignore)

print(letters)
# Counter({'e': 2, 'l': 2, 'H': 1, 'o': 1, 'B': 1, 'y': 1})

相关问题 更多 >