2017-04-11 65 views
-2

我對在循環字符串賦值,我需要找出多少(A,E,I,O,U)輸入。 我已經做了,但我覺得它太長了。我想縮短它,但我不知道如何。我怎樣才能使它更短,更好?

這是我的代碼:相反5變量計數和5不變的

x=input("enter the taxt that you need me to count how many (a,e,i,o,u) in it:") 

a=len(x) 

x1=0 

x2=0 

x3=0 

x4=0 

x5=0 

for i in range(a): 
    h=ord(x[i]) 

    if h == 105: 
     x1+=1 
    elif h == 111: 
     x2+=1 
    elif h == 97: 
     x3+=1 
    elif h == 117: 
     x4+=1 
    elif h == 101: 
     x5+=1 

print("There were",x3,"'a's") 
print("There were",x5,"'e's") 
print("There were",x1,"'i's") 
print("There were",x2,"'o's") 
print("There were",x4,"'u's") 
+1

我們應_guess_,這是... Python的? – deceze

+0

是的,它是蟒蛇,很抱歉沒有提及的是 – abdulraman

+2

可能的複製[如何計算在Python元音和輔音?](http://stackoverflow.com/questions/43164161/how-to-count-vowels-and-consonants -in的Python) – BWMustang13

回答

0

根據this question簡單的方法:

x = input("Enter the text that you need me to count how many (a,e,i,o,u) are in it:") 

print("There were", x.count('a'), "'a's") 
print("There were", x.count('e'), "'e's") 
print("There were", x.count('i'), "'i's") 
print("There were", x.count('o'), "'o's") 
print("There were", x.count('u'), "'u's") 
0

比較使用字典:

h = {105: 0, 111: 0, 97: 0, 117: 0, 101: 0} 

或 - 更好 -

h = {'i': 0, 'o': 0, 'a': 0, 'u': 0, 'e': 0} 

所以完整的代碼將

x = input("Enter the text that you need me to count how many (a,e,i,o,u) in it: ") 
h = {'i': 0, 'o': 0, 'a': 0, 'u': 0, 'e': 0} 

for i in x:    # there is no need to index characters in the string 
    if i in h: 
     h[i] += 1 

for char in h: 
    print("There were {} '{}'s".format(h[char], char)) 
1

您只需定義你在一個字符串關心(元音字母)字符的列表,然後使用dictionary comprehension。這段代碼會打印出你想要什麼,也讓你與所有存儲在字典中的值稱爲vowel_count

vowels = 'aeiou' 

x=input("enter the taxt that you need me to count how many (a,e,i,o,u) in it:") 

vowel_count = {vowel: x.count(vowel) for vowel in vowels} 

for vowel in vowels: 
    print("There were ",vowel_count[vowel]," '", vowel, " 's") 
相關問題