【发布时间】:2014-06-26 08:18:44
【问题描述】:
我尝试定义一个函数来按频率降序打印单词的字母,使用字典和元组。两个类似的问题是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。请修复代码。非常感谢。
【问题讨论】:
-
请修正代码标识。
-
请修正你的缩进,你的代码在逻辑上很难理解。另外,究竟是什么不起作用?
-
不工作是什么意思?因错误而崩溃?输出不正确?鼻恶魔感染?
-
Please read this 了解什么是主题“修复我的代码”问题。正如发布的那样,这显然是题外话,我已投票关闭它。
标签: python string python-3.x dictionary tuples