1
所以我正在写一个非常基本的函数,它接受一个字符串并返回列表中最常见的字符。出于某种原因,它陷入了循环。下面的代码:创建一个函数,因为某种原因陷入循环
def frequent(string, amount):
'''frequent(str) --> list
This function takes a string and returns a list of the
most frequent characters in order, without repetition.'''
values = []
common = ''
while len(values) != amount:
for char in string:
if string.count(char) > string.count(common):
common = char
values.append(char)
string = string.strip(char)
return values
改为查看['collections.Counter()'对象](https://docs.python.org/2/library/collections.html#collections.Counter);它可以开箱即用:'返回Counter(string).most_common()[0] [0]'。 –