2016-03-02 75 views
1

我有一個小的家庭作業問題,讓我的Python函數返回正確的值。Python函數的字典

分配:

Here is an example dictionary:

word_freq = {'the': 58, 'people': 6, 'beautiful': 8, 'cats': 13} 

Write a function that takes as parameters: a word frequency dictionary and a threshold number with is an integer. This function should return a result that is a list of all the words whose frequency is greater than the threshold.

For example, suppose that you name your function top_words. If you call the function with the dictionary above and the threshold of 10:

top_words(word_freq, 10) you should get the result [‘the’, ‘cats’] 

我的代碼:

def frequencylist(frequentwords, threshold): 
    for keys in frequentwords: 
     if key > threshold: 
      print(keys) 

試運行:

frequentwords= {'hello':30, 'yellow':4, 'red':10, 'blue':35, 'orange':100} 
frequencylist(frequentwords, 10) 

...我得到這個錯誤:

Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
File "<stdin>", line 3, in frequencylist 
TypeError: unorderable types: str() > int() 
+0

未來,請採取簡單的調試步驟:打印出來的在錯誤點之前發現值。再次運行;最後的輸出可能會清楚地顯示你的問題。 – Prune

回答

2

鑰匙是單詞;您的閾值是一個整數。您無法將這些類型與>進行比較。我想你的意思比較值:

for key, value in frequentwords.items(): 
    if value > threshold: 
    print(key) 

這將產生所需的輸出:

blue 
orange 
hello 

如果你也想紅色,您需要更改比較> =

+0

謝謝你的工作,雖然我不得不改變.iteritems項目它說該字典沒有該屬性 – user256107

+0

哎呀!我使用Python 2.7進行編程,並且在回答問題時有時會忘記切換。我很高興你明白了。我會編輯答案。 – Prune

1

你的功能不太正確。當你迭代(循環)字典時,你只能訪問鍵值。您需要使用內置的iteritems()items()函數來獲取密鑰和值。

def above_thresh(someDict, thresh): 
     return [field for field, value in someDict.iteritems() if value > thresh] 

In [6]: above_thresh(frequentwords, 10) 
Out[6]: ['blue', 'orange', 'hello'] 

或者,您也可以解決你的方法是這樣的:

def frequencylist(frequentwords, threshold): 
    toRet = [] 
    for keys in frequentwords: 
     if frequentWords[key] > threshold: 
       toRet.append(key) 
    return toRet 
1

你可以只是這樣做:

print [k for k,v in word_freq.items() if v>=10] 

它看起來像這樣的方法:

def frequencylist(frequentwords, threshold): 
    return [k for k,v in word_freq.items() if v>=threshold]