2017-06-20 99 views
0

我一直在使用Sorting_Dictionary中提供的解決方案根據值排序字典。我知道字典不能像這樣排序,但一個排序的斑點列表可以獲得。通過排序字典在python通過使tuplles排序列表不起作用

完整代碼:

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) 

這裏幫手是返回一個字典是進行排序的方法。字典是這樣的{爸爸: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) 

我們如何解釋這種現象?

+0

什麼是'helper',它的get()方法做了什麼? – DyZ

+0

歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)適用於此處。在發佈您的MCVE代碼並準確描述問題之前,我們無法爲您提供有效的幫助。 我們應該能夠將發佈的代碼粘貼到文本文件中,並重現您描述的問題。 – Prune

+0

我已經更新了關於幫助器,但這個get()方法是標準的,它返回對應於一個鍵的值並返回缺省值的鍵不存在 –

回答

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

根據用於排序(https://docs.python.org/3/library/functions.html#sorted)的文檔,第二個參數是創建從每個列表元素比較鍵的功能,所以不是字典作爲一個整體。

Word_count_new.items()返回一個元組的iterable(在python3中,python2中的列表),這是傳遞給你的關鍵函數的東西。如果你希望你的比較鍵是工作頻率的基礎(第二個元素),你想返回這個函數中的第二個元素(x[1],其中x是獲得比較的單個元組)。

爲了解釋你得到的隨機輸出,你的密鑰是Word_count_new.get。由於你的字典沒有元組作爲鍵,所以默認值是None。

+0

「傳遞一個元組到這可能會導致一些未定義的行爲_」 - 爲什麼這樣? – DyZ

+3

傳遞'tuple'的行爲是完全定義的:'.get'不會找到那個元組,並返回'None'。由於'sorted'確保穩定,並且'None'總是與None相比較,所有東西都會按照迭代'.items'通常產生的順序返回。 –

+0

謝謝!有效。但get函數也會創建該值作爲比較鍵,那麼它爲什麼不起作用? –