我正在寻找一个程序,我输入一个单词或一个短语,它计算输入中的元音数量,然后返回每个元音的数量。我已经这样做了,但我的代码很长,我想知道如何更有效地编写代码。
如何减少我使用的for循环量?
text = input("enter string:")
vowels = ["a","e","i","o","u"]
count = 0
for letters in text:
if letters in vowels:
count = count + 1
print ("vowel count is:",count)
numA = 0
numE = 0
numI = 0
numO = 0
numU = 0
for a in text:
if a in "a":
numA = numA + 1
for e in text:
if e in "e":
numE = numE + 1
for i in text:
if i in "i":
numI = numI + 1
for o in text:
if o in "o":
numO = numO + 1
for u in text:
if u in "u":
numU = numU + 1
print ("a occurs",numA)
print ("e occurs",numE)
print ("i occurs",numI)
print ("o occurs",numO)
print ("u occurs",numU)
答案 0 :(得分:6)
使用dict
:
vowels = ["a", "e", "i", "o", "u"]
# We use a dict to count the vowels.
# It is initialized with 0 for every vowel.
count = {v: 0 for v in vowels}
# Loop over every character in the input.
for c in "foo bar baz":
# If the character is a vowel, increment its count.
if c in vowels:
count[c] = count[c] + 1
print(count)
输出:
{'i': 0, 'u': 0, 'a': 2, 'o': 2, 'e': 0}
答案 1 :(得分:1)
作为@Lutz Horn答案的补充,您可以缩短它,并根据需要计算不同元音的数量:
text = input("enter string:")
# counts the number of different vowels
no_vowels = len(set(text).intersection("aeiou"))
# this is a dict comprehension, it constructs a dict with a vowel as key and the occurrence count as key
counts = {vowel: text.count(vowel) for vowel in "aeiou"}
# then you can print the number of occurrences from each item
print("vowel count is:", no_vowels)
for vowel in "aeiou":
print(vowel, "is used", count[vowel], "times")
或者你可以将它减少到4个可读行,如果你不需要将计数保存在变量中,只需要打印它们:
text = input("enter string:")
print("vowel count is", len(set(text).intersection("aeiou")))
for vowel in "aeiou":
print(vowel, "occurs", text.count(vowel), "times")
或者你可以使用内置的collections.Counter Python,它提供了最佳的性能和功能:
from collections import Counter
text = input("enter string:")
counter = Counter(text)
# counter now contains the counts for all letters, not only vowels
for vowel in "aeiou":
print(vowel, "occurs", counter[vowel], "times")
# this one is trickier, it is a sum of boolean, which returns the number of True
print("vowel count is:", sum(vowel in counter for vowel in "aeiou"))
答案 2 :(得分:0)
您可以使用count()
:
number_of_a = text.count('a')
number_of_e = text.count('e')
...
和元音总数:
number_of_vowels = sum(1 for x in text if x in 'aeiou')
答案 3 :(得分:0)
我喜欢上面显示的字典示例,但如果您想稍微改变,可以执行以下操作:
使用数组跟踪每个元音的计数。
vowelArray = [0, 0, 0, 0, 0]
inputStr = "This is the string to loop over"
for char in inputStr:
if char == "a":
vowelArray[0] += 1
if char == "e":
vowelArray[1] += 1
if char == "i":
vowelArray[2] += 1
if char == "o":
vowelArray[3] += 1
if char == "u":
vowelArray[4] += 1
print(vowelArray)
答案 4 :(得分:0)
尝试尽可能保留原始代码,这是您的算法,使用dict
- 来计算元音:
#text = input("enter string:")
text = "phraseanditcountsthenumberofvowels"
vowels = {"a":0,"e":0,"i":0,"o":0,"u":0}
for letter in text:
letter = letter.lower()
if letter in vowels:
vowels[letter] += 1
print(vowels)