這裏是我的代碼功能不會改變參數通緝
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語句,但不是功能外..
您必須在函數末尾返回* count_dict *,然後使用返回的值。如果您不聲明它們是全局的,則函數內部修改的變量只屬於該函數的名稱空間。要獲取函數範圍外的變量值,必須使用* return *語句 – Jalo
,但該函數的返回類型爲None。這個函數的目的是接受發送的內容並改變它自己的內容 –
'count_dict = {}'表示你正在創建一個新的本地字典,並且不再處理已經傳入函數的字典。任何方式,它不是真正的Pythonic修改已作爲參數傳入的字典,你應該總是'返回'你想要的結果 – UnholySheep