English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial básico Python

Controle de fluxo Python

Função do Python

Tipos de Dados do Python

Operações de arquivos Python

Objetos e classes Python

Data e hora Python

Conhecimentos avançados Python

Manual de referência Python

Programa Python calcula o número de vogais

Python example in full

Neste programa, você aprenderá a usar dicionários e compreensão de listas para calcular o número de vogais em uma string.

Para entender este exemplo, você deve conhecer o seguinteProgramação PythonTema:

Código-fonte: Uso de dicionário

# Python program to calculate the number of each vowel
# Vowel string
vowels = 'aeiou'
ip_str = 'Hello, have you tried our tutorial section yet?'
# Use the casefold method to convert all uppercase letters in the string to lowercase.
ip_str = ip_str.casefold()
# Use each vowel letter as the key and a dictionary with a value of 0
count = {}.fromkeys(vowels,0)
# Count the number of vowels
for char in ip_str:
   if char in count:
       count[char] += 1
print(count)

Output result

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

Here, we take a string stored in ip str. Using the casefold() method, we make it suitable for case-insensitive comparison. Essentially, this method returns the lowercase version of the string.

We use the dictionary method fromkeys() to construct a new dictionary, with each vowel as its key and all values equal to 0. This is the initialization of the count.

Next, we usefor looptraverse the input string.

In each iteration, we check if the character is in the dictionary key (if it is a vowel, it is True), and if it is True, we increase the value1.

Source code: using list and dictionary comprehension

# Use dictionary and list comprehension
ip_str = 'Hello, have you tried our tutorial section yet?'
# Make it suitable for case-insensitive comparison
ip_str = ip_str.casefold()
# Count vowels
count = {x:sum([1 for char in ip_str if char == x] for x in 'aeiou'}
print(count)

The program'sOutputthe same as above.

Here, we willlistUnderstanding nested inIn the dictionary list,To calculate vowels in a single line.

However, since we iterate over the entire input string for each vowel, the program is slower.

Python example in full