简体   繁体   中英

Is it possible to use the Counter function to see the ocurrences of elements in a list within a bigger list?

I am asked to make code that counts the ocurrence of each vowel in a single inputed word. Case insensitive.

So I basically want to count the ocurrence of different elements within a list. They way I thought of this is to create a list. vowels=( "a","e","i","o","u" )

Then I input the word, lowering it, etc.

from collections import Counter
x = input()
y = x.lower()
z = list(y)

Then I want to use counter so it can count all of the vowels at once.

C = z.Counter(vowels) 
print(C)

But when I run the software it shows me

AttributeError: 'list' object has no attribute 'Counter'

So what I am doing wrong? Or can you just not use counter the same way that you use count?

(I already solved the excercise using count but I'm trying to find a elegant more concise solution.)

This is the whole code I'm trying to make work:

from collections import Counter
x = input()
y = x.lower()
z = list(y)
vowels=[ "a" ,"e" ,"i" ,"o" ,"u" ]

C = z.Counter(vowels)

print(C)

Counter is not an attribute nor a method of list. Try this instead:

vowels = ("a", "e", "i", "o", "u")
x = input("Enter a word:") # input: aeiai
y = x.lower()
vowels_counter = {k: v for k, v in Counter(y).items() if k in vowels}
print(vowels_counter) # output: {'a': 2, 'e': 1, 'i': 2}

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