【问题标题】:Sort value in dictionary by value in Python在Python中按值对字典中的值进行排序
【发布时间】:2016-01-07 12:18:47
【问题描述】:

我在 Python 中有这样的东西来计算文本中字符的频率,但我无法对字典“v”上的值进行排序。

abcedario='abcdefghijklmnopqrstvuxwyz'
v = {}
count = 0
for c in abcedario:
    count = 0
    for char in text:
        if c == char:
            count = count +1
            v[c] = count
            sorted(v.items(), key=lambda x:x[1])
print v

我尝试在 stackoverflow 上搜索,但从未解决我的问题,输出的方面是这样的:

{'a': 2, 'b': 4, 'e': 4, 'd': 36, 'g': 31, 'f': 37, 'i': 14, 'h': 4, 'k': 51, 'j': 31, 'l': 34, 'n': 18, 'q': 13, 'p': 2, 'r': 9, 'u': 1, 't': 1, 'w': 36, 'v': 15, 'y': 14, 'x': 8, 'z': 10}

我想按值排序,所以它与其他帖子不同。

【问题讨论】:

  • 更大的问题是sorted返回一个新集合而不是就地排序
  • @ZdaR OrderedDict,大概?
  • 我不认为这是重复的,另一个问题是关于按键排序。
  • 顺便说一句,您的代码非常效率低下。您不需要有一对嵌套的 for 循环。

标签: python arrays sorting dictionary text


【解决方案1】:

你可以使用计数器

from collections import Counter
text = "I have something like this in Python to count the frequency of characters in a text, but i can't sort the values on the dictionary"
print(Counter(text))

输出:

Counter({' ': 24, 't': 15, 'e': 11, 'n': 9, 'h': 8, 'i': 8, 'o': 8, 'a': 7, 'c': 6, 's': 5, 'r': 5, 'u': 4, 'y': 3, 'f': 2, 'l': 2, 'v': 2, "'": 1, 'q': 1, 'd': 1, 'I': 1, 'm': 1, 'g': 1, 'b': 1, 'x': 1, ',': 1, 'P': 1, 'k': 1})

【讨论】:

    【解决方案2】:

    如果只想按顺序打印,只需打印sorted的输出即可:

    abcedario='abcdefghijklmnopqrstvuxwyz'
    v = {}
    count = 0
    for c in abcedario:
        count = 0
        for char in text:
            if c == char:
                count = count +1
                v[c] = count
    print sorted(v.items(), key=lambda x:x[1])
    

    对于text = "helloworld",你会得到:

    [('e', 1), ('d', 1), ('h', 1), ('r', 1), ('w', 1), ('o', 2), ('l', 3)]  
    

    【讨论】:

    • 就是这样!非常感谢。
    【解决方案3】:

    python 字典是项目的无序集合。因此,无法对其进行排序。 尝试从collections 调查OrderedDict

    【讨论】:

    • 那么,我如何在没有字典的情况下使用其他东西进行排序?我是 python 新手。
    • 你想让值按键排序吗?
    • 按价值。但我不想使用导入,上面的解决方案可以解决我的问题。
    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 2014-10-19
    • 2014-07-28
    • 2011-02-09
    相关资源
    最近更新 更多