我尝试定义一个函数,以以频率递减的顺序打印单词的字母,使用字典和元组。两个类似的问题是Counting repeated characters in a string in Python和How to write a function that takes a string and prints the letters in decreasing order of frequency?,但区别在于排序(按频率)部分和算法。
这是我写的: -
def most_frequent(string):
d = dict() #Created a dictionary
for c in string:
d[c] = d.get(c,0)+1 #Employed the get method to get the value of the key c
t = d.items() #Created a list of tuples of key-value pairs
for letter, frequency in t:
letter, frequency = frequency, letter #Swapped the elements of the tuples
t.sort(reverse = True) #Sorting in descending order
for frequency, letter in t:
print (frequency," ",letter)
当我用“bookshopkeeper”作为参数调用函数时产生的错误消息是: -
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
most_frequent("bookshopkeeper")
File "<pyshell#1>", line 8, in most_frequent
t.sort(reverse = True)
AttributeError: 'dict_items' object has no attribute 'sort'
我使用get方法来消除if条件的使用。我正在使用python 3.3。请修复代码。非常感谢。
答案 0 :(得分:3)
您最好使用collections.Counter
。
dct = collections.Counter(string)
print(dct.most_common())
print(list(reversed(dct.most_common()))) # least common :-)