这里是我的代码功能不会改变参数通缉
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