簡體   English   中英

在Python中計算相等的字符串

[英]Counting equal strings in Python

我有一個字符串列表,其中一些是相同的。 我需要一些可以計算相同字符串的腳本。 例如:

我有一個單詞列表:

“屋”
“夢想”
“樹”
“樹”
“屋”
“天空”
“屋”

輸出應該如下所示:

“眾議院” - 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

這很簡單( words是您要處理的單詞列表):

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

它不需要任何額外的模塊。

測試

對於以下words值:

words = ['House', 'Dream', 'Tree', 'Tree', 'House', 'Sky', 'House']

它會給你以下結果:

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

它能回答你的問題嗎?

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)

我將擴展Tadeck的答案來打印結果。

for word in set(words):
  print '''"%s" - %d''' %(word, words.count(word))

下面的代碼可以讓你按預期方式

stringvalues = ['House', 'Home', 'House', 'House', 'Home']
for str in stringvalues:
    if( str in newdict ):
        newdict[str] = newdict[str] + 1
    else:
        newdict[str] = 1
all = newdict.items()
for k,v in all:
    print "%s-%s" % (k,v)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM