2016-11-15 74 views
0
text = 'hello' 
vowels = 'aeiou' 


for char in text.lower(): 
    if char in vowels: 




print(minimum_dict) 

我該怎麼做才能讓我編寫的這個程序打印出「元音x出現的次數」。從字典中打印語句

我試過但我無法讓它正常工作,程序是在哪裏有一個詞的輸入,它檢查發現最不頻繁的元音。

回答

1

您可以遍歷字典來獲取密鑰和值。 items返回一個元組對。

包括以下部分代碼打印所需的結果:

for key,value in minimum_dict.items(): 
    print("Vowel ", key, "occurs", value ," times") 

minimum_dict.items()返回,因爲他們key到字典項的列表和它相關的value:在這種情況下

value相當於minimum_dict[key]

+2

只有代碼答案不是很有幫助。參考[答]並添加解釋。也沒有必要複製他的整個代碼集,只有你已經改變的部分 – TemporalWolf

+0

@makavelllli我添加了一個編輯,但是在這種情況下,短版本是'value'相當於'minimum_dict [key]'。這就是'minimum_dict.items()'爲你所做的。 – TemporalWolf

0
for vowel, occurrences in minimum_dict.items(): 
    print("vowel", vowel, "occurs ", occurrences, "times") 

通過您的最低限度地存在的元音的字典這將循環,並且對於每個元音/出現對將打印字符串「母音」,則實際元音,字符串「發生」,出現的次數,並字符串「times」。

print()函數接受任意數量的未命名參數並將它們轉換爲字符串,然後將它們寫入輸出。

1

您的代碼可以使用collections.defaultdict()作爲被簡化:

from collections import Counter 
Counter(text) 

>>> from collections import defaultdict 
>>> text = 'hello' 
>>> vowels = 'aeiou' 
>>> vowel_count = defaultdict(int) 
>>> for c in text: 
...  if c in vowels: 
...   vowel_count[c] += 1 
... 
>>> vowel_count 
{'e': 1, 'o': 1} 

如果你有來存儲所有的字符個數,這個代碼可以進一步使用collections.Counter()爲簡化