简体   繁体   中英

Counting equal strings in Python

I have a list of strings and some of them are equal. I need some script which would count equal strings. Ex:

I have a list with some words :

"House"
"Dream"
"Tree"
"Tree"
"House"
"Sky"
"House"

And the output should look like this:

"House" - 3
"Tree" - 2
"Dream" - 1
and so on

Use collections.Counter() . It is designed for exactly this use case:

>>> 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

Solution

This is quite simple ( words is a list of words you want to process):

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

It does not require any additional modules.

Test

For the following words value:

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

it will give you the following result:

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

Does it answer your question?

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)

I will extend Tadeck's answer to print the results.

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

Below code should get you as expected

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM