【问题标题】:Writing a function to print letters of a string according to their frequency compalsarily using dictionary and tuple [closed]使用字典和元组编写一个函数来根据它们的频率打印字符串的字母[关闭]
【发布时间】:2014-06-26 08:18:44
【问题描述】:

我尝试定义一个函数来按频率降序打印单词的字母使用字典和元组。两个类似的问题是Counting repeated characters in a string in PythonHow 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


【解决方案1】:

你最好使用collections.Counter

dct = collections.Counter(string)
print(dct.most_common())
print(list(reversed(dct.most_common())))  # least common :-)

【讨论】:

    猜你喜欢
    • 2017-08-30
    • 1970-01-01
    • 2021-08-10
    • 2012-01-13
    • 1970-01-01
    • 2021-06-05
    • 2021-03-05
    • 2022-12-04
    • 2019-06-04
    相关资源
    最近更新 更多