我正在研究一个实验室(在Python 3中),它要求我在最常出现的字符串中查找和打印字符。例如:
>>> print(maxCharCount('apple'))
['p']
这个想法是使用循环来做到这一点,但我对如何做到这一点很困惑。
答案 0 :(得分:2)
def maxCharCount(ss):
return max(ss, key=ss.count)
答案 1 :(得分:1)
def max_char_count(string):
max_char = ''
max_count = 0
for char in set(string):
count = string.count(char)
if count > max_count:
max_count = count
max_char = char
return max_char
print(max_char_count('apple'))
答案 2 :(得分:0)
因为你真的想要使用for循环:
a = 'apple'
m = set(a)
max = 0
for i in m:
if a.count(i) > max:
max = a.count(i)
编辑:我没看好,你实际上希望这封信不是它出现的次数所以我编辑这段代码:
a = 'apple'
m = set(a)
max = 0
p = ''
for i in m:
if a.count(i) > max:
max = a.count(i)
p = i
答案 3 :(得分:0)
def count(char, string):
c = 0
for s in string:
if char == s:
c += 1
return c
def max_char_count(string):
biggest = string[0]
for c in string:
if count(c,string) > count(biggest,string):
biggest = c
return biggest