0
我有這個示例代碼爲python Counter。在Python中的正則表達式匹配項計數器
from collections import Counter
lst = ['item', 'itemm', 'iitem', 'foo', 'bar']
c = Counter(lst)
Counter({'bar': 1, 'foo': 1, 'iitem': 1, 'item': 1, 'itemm': 1})
如果我做c['item']
我得到1
,但我想3
由於列表中的錯別字。
我試過以下,它並沒有給我3
但我仍然有它的工作:
import re
for word in lst:
if re.search('item',word):
print(word,c[word])
item 1
itemm 1
iitem 1
有沒有一種比較有效的方法來做到這一點,而無需通過列表循環?
感謝您使用list_comprehension,沒有正則表達式的一個的速度要快得多。 – Leb