[英]how to make vowel counter and sum more concise and efficient? Python
我是Stack Overflow的新手,但是注意到它很有幫助,因此打開了這個社區。 只是好奇是否有任何方法可以使此元音計數器更簡潔/更有條理。 任何幫助將不勝感激,並且深入的回答也將是很棒的。 謝謝!
def vowel_count(str):
str = input("Please enter a sentence: ")
str1 = (str.lower())
#intialize count variable to zero
count = 0
#create a set of vowels
vowel = set("aeiou")
for alphabet in str1:
if alphabet in vowel:
count = count+1
print("Number of vowels in this sentence is: " , count)
print()
print("A,E,I,O,U")
print(*map(str.lower().count, "aeiou"))
vowel_count(str)
我在您的代碼示例中看到,您使用了一個名為str的變量。 不要這樣做,因為str是內置函數,這可能會導致問題。
那這個解決方案呢:
string = input().lower()
print(sum([string.count(i) for i in "aeiou"]))
首先,我得到輸入,我立即降低了輸入。 然后,我為每個元音使用string.count(i),在這種情況下,它返回i(元音之一)出現在字符串(輸入)中的次數。 然后,我在創建的數組上調用sum函數,該函數返回數組中所有元素的總和。 最后但並非最不重要的一點是,我只打印了此求和函數返回的值。
如果您不明白傳遞給sum函數的參數是一個數組,請查看List Comprehension主題。
我認為您應該使用Counter 。
from collections import Counter
In [1]: a = 'I am mayank'
In [5]: ans = Counter(a.lower())
In [6]: ans
Out[6]: Counter({' ': 2, 'a': 3, 'i': 1, 'k': 1, 'm': 2, 'n': 1, 'y': 1})
In [10]: ans['a']
Out[10]: 3
這將計算字符串中每個字母(包括元音)的出現情況。 這應該非常有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.