在Python中计算相等的字符串

2024-05-23 15:00:12 发布

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

我有一个字符串的列表,其中一些是相等的。我需要一些脚本来计算相等的字符串。例如:

我有一张单子上面写着:

“房子”
“梦想”
“树”
“树”
“房子”
“天空”
“房子”

输出应该如下所示:

“房子”-3
“树”-2
“梦想”-1
等等


Tags: 字符串脚本列表单子天空梦想房子
3条回答

使用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是要处理的单词列表):

result = {}
for word in set(words):
    result[word] = words.count(word)

它不需要任何附加模块。在

试验

对于以下words值:

^{pr2}$

结果如下:

>>> result
{'Dream': 1, 'House': 3, 'Sky': 1, 'Tree': 2}

它能回答你的问题吗?在

相关问题 更多 >