简体   繁体   中英

find number of vowels in a string

I have a string of letters as input.
input:

my_str = 'soumendra_in_stackoverflow'

I want output like below. Where all the vowels should be printed along with their corresponding count in a dictionary.
output needed :

{'a': 2, 'e': 2, 'i': 1, 'o': 3, 'u': 1}

For this I have written the following program:

ans_dict = {}
for letter in my_str:
    if letter in ['a', 'e', 'i', 'o', 'u']:
        ans_dict[letter] = ans_dict.get(letter, 0) + 1
print(ans_dict)

It works. However, how to write this same logic in a single line (maybe using dictionary comprehension) without using collections.Counter ?
I have tried this but it's failing.

{x: + 1 for x in a if x in ['a', 'e', 'i', 'o', 'u'] }

You can use str.count and thus write the dictionary comprehension with:

result = { v: my_str.count(v) for v in "aeiou" }

But this thus results in enumerating over the my_str five times. Like @DSM however says, .count(..) typically works rather fast (my guess is that it is implemented at the interpreter level, so it does not have to "iterate" over the collection).

Personally I think that a Counter here would be better, since

  1. it is designed exactly for the purpose of counting things, and furthermore it wraps data into an interface that will enforce constraints (unless there is a bug in the Counter , the counts will definitely be correct, whereas a custom made algorithm can still have a "silly" mistake, yes here that is very unlikely, but it is still better to avoid that); and
  2. it provides an nice interface to do all sorts of things with these counts (for example counter1 & counter2 will construct a new Counter , with the minimum counts of every element).

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