【问题标题】:sorting key-value pairs in python在python中对键值对进行排序
【发布时间】:2016-11-12 14:27:20
【问题描述】:

我正在编写一个如下所示的小程序

"""Count words."""
    # TODO: Count the number of occurences of each word in s

    # TODO: Sort the occurences in descending order (alphabetically in case of ties)

    # TODO: Return the top n words as a list of tuples (<word>, <count>)    
from operator import itemgetter

def count_words(s, n):
    """Return the n most frequently occuring words in s."""

    t1=[]
    t2=[]
    temp={}
    top_n={}
    words=s.split()
    for word in words:
        if word not in temp:
            t1.append(word)
            temp[word]=1
        else:
            temp[word]+=1

    t1 = sorted(temp,key=temp.get,reverse=True) # to get sorted keys
    t2 = sorted(temp.values(),reverse=True) # to get sorted values
    top_n = dict(zip(t1,t2))
    print top_n

    return 


def test_run():
    """Test count_words() with some inputs."""
    count_words("cat bat mat cat bat cat", 3)
    count_words("betty bought a bit of butter but the butter was bitter", 3)


if __name__ == '__main__':
    test_run()

我只是想对键值对进行排序。我有以下问题:

  1. 在上面的程序中,当我打印两个排序列表的合并时,它只显示未排序的合并
  2. 如何通过 python 函数获取排序的键值对,我正在使用的当前 fxn 返回键或值。我们能以某种方式得到两者吗?

【问题讨论】:

标签: python sorting keyvaluepair


【解决方案1】:

根据顶部的注释,您要返回键/值元组的列表。因此,您希望按值对字典的 items 进行排序:

sorted(temp.items(), key=itemgetter(1), reverse=True)

请注意,您将键和值分开排序的策略将不起作用——您最终会将键与不属于一起的值匹配。

另请注意,collections.Counter 已针对执行此任务进行了优化(请参阅.most_common

【讨论】:

    【解决方案2】:
    sorted([(value,key) for (key,value) in temp.items()])
    

    【讨论】:

      【解决方案3】:

      您可以像这样按值对字典进行排序:

      sorted(temp.items(), key = lambda x: x[1], reverse = True)
      

      【讨论】:

        猜你喜欢
        • 2019-08-17
        • 2012-07-02
        • 2018-03-06
        • 1970-01-01
        • 1970-01-01
        • 2015-06-03
        • 1970-01-01
        • 1970-01-01
        • 2012-04-28
        相关资源
        最近更新 更多