2024-05-23 15:00:12 发布
网友
我有一个字符串的列表,其中一些是相等的。我需要一些脚本来计算相等的字符串。例如:
我有一张单子上面写着:
“房子” “梦想” “树” “树” “房子” “天空” “房子”
输出应该如下所示:
“房子”-3 “树”-2 “梦想”-1 等等
使用collections.Counter()。它正是为这个用例而设计的:
>>> import collections >>> seq = ["House", "Dream", "Tree", "Tree", "House", "Sky", "House"] >>> for word, cnt in collections.Counter(seq).most_common(): print repr(word), '-', cnt 'House' - 3 'Tree' - 2 'Sky' - 1 'Dream' - 1
from collections import defaultdict counts = defaultdict(int) for s in strings: counts[s] += 1 for (k, v) in counts.items(): print '"%s" - %d' % (k, v)
这很简单(words是要处理的单词列表):
words
result = {} for word in set(words): result[word] = words.count(word)
它不需要任何附加模块。在
对于以下words值:
结果如下:
>>> result {'Dream': 1, 'House': 3, 'Sky': 1, 'Tree': 2}
它能回答你的问题吗?在
使用collections.Counter()。它正是为这个用例而设计的:
解决方案
这很简单(
words
是要处理的单词列表):它不需要任何附加模块。在
试验
对于以下
^{pr2}$words
值:结果如下:
它能回答你的问题吗?在
相关问题 更多 >
编程相关推荐