我一直在checkio.com上解决问题,其中一个问题是:“编写一个函数来查找在给定字符串中出现最大次数的字母”
最重要的解决方案是:
import string
def checkio(text):
"""
We iterate through latin alphabet and count each letter in the text.
Then 'max' selects the most frequent letter.
For the case when we have several equal letter,
'max' selects the first from they.
"""
text = text.lower()
return max(string.ascii_lowercase, key=text.count)
当它被用作max函数中的键时,我不明白text.count是什么.
编辑:抱歉没有更具体.我知道程序的功能以及str.count()的功能.我想知道text.count是什么.如果.count是一种方法,那么它不应该跟着括号吗?
解决方法:
key = text.count是计算所有字母出现在字符串中的次数,然后你取所有这些数字中最大的数字来获得最常出现的字母.
运行以下代码时,结果为e,如果算数,则为最常用的字母.
import string
def checkio(text):
"""
We iterate through latin alphabet and count each letter in the text.
Then 'max' selects the most frequent letter.
For the case when we have several equal letter,
'max' selects the first from they.
"""
text = text.lower()
return max(string.ascii_lowercase, key=text.count)
print checkio('hello my name is heinst')
标签:python
来源: https://codeday.me/bug/20190528/1173441.html