import re
from collections import Counter
data_items = ['abc','123data','dataxyz','456','344','666','777','888','888', 'abc', 'xyz']
search = ['abc','123','xyz','456']
to_search = re.compile('|'.join(sorted(search, key=len, reverse=True)))
matches = (to_search.search(el) for el in data_items)
counts = Counter(match.group() for match in matches if match)
# Counter({'abc': 2, 'xyz': 2, '123': 1, '456': 1})
>>> data_items = ['abc','123data','dataxyz','456','344','666','777','888','888', 'abc', 'xyz']
>>> search = ['abc','123','xyz','456']
>>> result = {k:0 for k in search}
>>> for item in data_items:
for search_item in search:
if search_item in item:
result[search_item]+=1
>>> result
{'123': 1, 'abc': 2, 'xyz': 2, '456': 1}
您可以使用
re.search
和collections.Counter
,例如:如果你不介意用字典的话(因为你说的是结构,这是一个更好的选择)。在
看来你也需要部分匹配。下面的代码是直观的,但可能不是有效的。也假设你对dict结果没问题。在
相关问题 更多 >
编程相关推荐