看看這個:
>>> from collections import Counter
>>> mystr = "AaAaaEeEiOoouuu"
>>> a,b = Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0]
>>> "the most frequent vowel is {} occurring {} times".format(a.upper(), b)
'the most frequent vowel is A occurring 5 times'
>>>
這裏是collections.Counter
參考。
編輯:
這是怎麼回事的一步一步的示範:
>>> from collections import Counter
>>> mystr = "AaAaaEeEiOoouuu"
>>> Counter(c for c in mystr.lower() if c in "aeiou")
Counter({'a': 5, 'o': 3, 'e': 3, 'u': 3, 'i': 1})
>>> # Get the top three most common
>>> Counter(c for c in mystr.lower() if c in "aeiou").most_common(3)
[('a', 5), ('o', 3), ('e', 3)]
>>> # Get the most common
>>> Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)
[('a', 5)]
>>> Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0]
('a', 5)
>>> a,b = Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0]
>>> a
'a'
>>> b
5
>>>
你好,謝謝你這個完美的作品!你能解釋一下櫃檯是如何爲我工作的嗎?特別是a,b =和最後的方括號。 – JamesDonnelly
@JamesDonnelly - 對,遲到對不起。我在我的文章中包含了一個分步演示。 – iCodez
你可以解釋一下這行(c在mystr.lower()中是否存在,如果c在「aeiou」中)?謝謝 – JamesDonnelly