Python将字典排序为升序单词列表

2024-06-16 13:55:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下示例代码:

articles = {'article1.txt': {'harry': 3, 'hermione': 2, 'ron': 1},
 'article2.txt': {'dumbledore': 5, 'hermione': 3},
 'article3.txt': {'harry': 5, 'hermione': 5}}
keywords = ['hermione', 'dumbledore']

def recommend_articles(articles, keywords):

    def max_count(key): 
      result = 0 
      for names in articles.keys():
        for name, count in articles[names].items():
          if name in keywords:
            result += count
            print name, count, result
      return result

    article_list = sorted(articles.keys(), key=max_count, reverse = True)
    print article_list

从函数中打印出来的是:

hermione 2 2
hermione 5 7
dumbledore 5 12
hermione 3 15
hermione 2 2
hermione 5 7
dumbledore 5 12
hermione 3 15
hermione 2 2
hermione 5 7
dumbledore 5 12
hermione 3 15
['article1.txt', 'article3.txt', 'article2.txt']

我也不知道发生了什么。我应该得到:

>>>recommended_articles(articles, keywords)
['article2.txt', 'article3.txt', 'article1.txt']

但是我的函数始终返回['article1.txt', 'article3.txt', 'article2.txt'],不管我是否更改关键字

如果您能帮忙,我们将不胜感激


Tags: nameintxtdefcountresultarticlesmax
2条回答

我想这就是你需要的:

articles = {'article1.txt': {'harry': 3, 'hermione': 2, 'ron': 1},
 'article2.txt': {'dumbledore': 5, 'hermione': 3},
 'article3.txt': {'harry': 5, 'hermione': 5}}
keywords = ['hermione', 'dumbledore']

def recommend_articles(articles, keywords):

    def max_count(key): 
      result = 0 
      for name in articles[key].keys():
        if name in keywords:
          result = result + articles[key][name]
      return result

    article_list = sorted(articles.keys(), key=max_count, reverse = True)
    print article_list

print(recommend_articles(articles, keywords))

只是一个信息:文章是以dict of dict的形式出现的,所以你总是会得到无序的输出。试着对文章使用有序的dict

相关问题 更多 >