2016-12-05 76 views
1

這裏是我的代碼功能不會改變參數通緝

def common_words(count_dict, limit): 
    ''' 
    >>> k = {'you':2, 'made':1, 'me':1} 
    >>> common_words(k,2) 
    >>> k 
    {'you':2} 
    ''' 
    new_list = list(revert_dictionary(count_dict).items())[::-1] 
    count_dict = {} 
    for number,word in new_list: 
     if len(count_dict) + len(word) <= limit: 
      for x in word: 
       count_dict[x] = number 

    print (count_dict) 





def revert_dictionary(dictionary): 
    ''' 
    >>> revert_dictionary({'sb':1, 'QAQ':2, 'CCC':2}) 
    {1: ['sb'], 2: ['CCC', 'QAQ']} 
    ''' 
    reverted = {} 
    for key,value in dictionary.items(): 
     reverted[value] = reverted.get(value,[]) + [key] 
    return reverted 


count_dict = {'you':2, 'made':1, 'me':1} 
common_words(count_dict,2) 
print (count_dict) 

我的預期是有count_dict變量改爲{「你」:2}。 它確實做工精細的功能的print語句,但不是功能外..

+0

您必須在函數末尾返回* count_dict *,然後使用返回的值。如果您不聲明它們是全局的,則函數內部修改的變量只屬於該函數的名稱空間。要獲取函數範圍外的變量值,必須使用* return *語句 – Jalo

+0

,但該函數的返回類型爲None。這個函數的目的是接受發送的內容並改變它自己的內容 –

+0

'count_dict = {}'表示你正在創建一個新的本地字典,並且不再處理已經傳入函數的字典。任何方式,它不是真正的Pythonic修改已作爲參數傳入的字典,你應該總是'返回'你想要的結果 – UnholySheep

回答

0

如前所述,問題在於count_dict = {}您沒有更改傳入的字典,而是創建一個新字典,並且所有後續更改都在該新字典上完成。傳統的方法是隻返回新的字典,但似乎你不能這樣做。

或者,不是將值添加到新字典中,而是反轉條件並從現有字典中刪除值。儘管如此,您不能在條件中使用len(count_dict),並且必須使用另一個變量來跟蹤已添加到(或者說,而不是從字典中刪除)的元素。

def common_words(count_dict, limit): 
    new_list = list(revert_dictionary(count_dict).items())[::-1] 
    count = 0 
    for number,word in new_list: 
     if count + len(word) > limit: 
      for x in word: 
       del count_dict[x] 
     else: 
      count += len(word) 

還要注意的是,從字典返回revert_dictionary沒有特定的順序,太行new_list = list(revert_dictionary(count_dict).items())[::-1]不能保證給你在任何特定的順序items,也是如此。您可能需要在此處添加sorted並按計數進行排序,但我不確定是否真的需要這一點。

new_list = sorted(revert_dictionary(count_dict).items(), reverse=True) 
+0

非常感謝! –

-1

只寫

return count_dict 

下面

print count_dict 

在功能common_words()

和變化

common_words(count_dict,2) 

count_dict=common_words(count_dict,2) 

所以基本上你需要從函數的返回值,並將其存儲在您的變量。當你調用函數並給它一個參數時。它將其副本發送給該函數,而不是自身變量。

+0

如果你不想返回任何東西。不要將count_dict參數傳遞給函數。它會自動把全局count_dict變量 – Premraj

+0

謝謝你的建議!我只是簡單地彈出字典,使其全部爲空,然後再次添加,並且它工作正常! –

1

的問題,因爲別人已經寫的,是你的函數分配空字典count_dict

count_dict = {} 

當你這樣做,你修改局部變量count_dict,但程序主要部分中具有相同名稱的變量繼續指向原始字典。

您應該明白,您允許修改您在函數參數中傳遞的字典;只是不要用新的字典來代替它。爲了讓您的代碼,而無需修改其他任何工作,你可以把它刪了現有字典中的所有元素:

count_dict.clear() 

此修改已傳遞給函數的字典,刪除其elements--所有這你的意圖。也就是說,如果你正在執行一個新的計算,通常在你的函數中創建一個新的字典是一個好主意,並且用return返回它。