簡體   English   中英

通過創建tuplles的排序列表在python中對字典進行排序不起作用

[英]Sorting Dictionary in python by making a sorted list of tuplles doesn't work

我一直在使用Sorting_Dictionary中提供的解決方案根據值對字典進行排序。我知道字典無法進行這種排序,但可以獲得排序的tupple列表。

完整的代碼:

import sys
import pprint


def helper(filename):
    Word_count={}
    f=open(filename)
    for line in f:
        words=line.split()
        for word in words:
            word=word.lower()
            Word_count.setdefault(word,0)
            Word_count[word]+=1
    f.close()
    return Word_count

def print_words(filename):
    Word_count_new=helper(filename)
    sorted_count=sorted(Word_count_new.items(),key=Word_count_new.get,reverse=True)
    for word in sorted_count:
      pprint.pprint(word)

def print_top(filename):
    word_list=[]
    Word_count=helper(filename)
    word_list=[(k,v) for k,v in Word_count.items()]
    for i in range(20):
        print word_list[i] + '\n'
###

# This basic command line argument parsing code is provided and
# calls the print_words() and print_top() functions which you must define.
def main():
  if len(sys.argv) != 3:
    print 'usage: ./wordcount.py {--count | --topcount} file'
    sys.exit(1)

  option = sys.argv[1]
  filename = sys.argv[2]
  if option == '--count':
    print_words(filename)
  elif option == '--topcount':
    print_top(filename)
  else:
    print 'unknown option: ' + option
    sys.exit(1)

if __name__ == '__main__':
  main()

此函數產生問題:

def print_words(filename):
    Word_count_new=helper(filename)
    sorted_count=sorted(Word_count_new.items(),key=Word_count_new.get,reverse=True)
    for word in sorted_count:
        pprint.pprint(word)

這里的helper是一種返回要排序的字典的方法。 字典是這樣的{爸爸:1,媽媽:2,嬰兒:3}

但這不會產生排序的清單。 相反,輸出有點像這樣

('he', 111)
("hot-tempered,'", 1)
('made', 29)
('wise', 2)
('whether', 11)
('wish', 21)
('scroll', 1)
('eyes;', 1)
('this,', 17)
('signed', 2)
('this.', 1)

我們如何解釋這種行為?

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

根據sorted的文檔( https://docs.python.org/3/library/functions.html#sorted ),第二個參數是一個從每個列表元素創建比較鍵的函數,因此dict不能作為整個。

Word_count_new.items()返回一個可迭代的元組(在python3中為python2中的列表),這是傳遞給您的鍵函數的內容。 如果希望比較鍵基於工作頻率(第二個元素),則要在此函數中返回第二個元素( x[1] ,其中x是要比較的單個元組)。

為了解釋您得到的隨機輸出,您的密鑰是Word_count_new.get 由於您的字典沒有元組作為鍵,因此默認值為“無”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM