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]'。 –