返回两个词典,在单独的函数中使用每个词典

时间:2016-07-22 18:09:01

标签: python

def make(node):    # takes some input
  for reg_names in reg.names # dont worry about reg_names and reg.names
   if reg.size > 0:    #reg.size is an inbuilt function
    found_dict = {}   # first dictionary
    found_dict['reg.name'] = 'reg.size' # i want to save the name of the register : size of the register in the format name : size
   else:
    not_found_dict = {}   
    not_found_dict['reg.name'] = 'reg.size' #again, i want to save the name of the register : size of the register in the format name : size
return found_dict, not_found_dict

好的,你能告诉我是否从上面的for循环中,如果创建字典(found_dict和not_found_dict)的构造是正确的,假设reg.name和reg.size是有效的构造吗?

然后我想在power_one中使用found_dict,在function_two中使用not_found_dict,如下所示:

def function_one(input):   # should this input be the function 'make' as I only want found_dict?
  for name, size in found_dict.items():  #just for the names in found_dict
    name_pulled = found_dict['reg.name'] # save the names temporarily to name_pulled using the key reg.name of found_dict
    final_names[] = final_names.append(name_pulled) #save names from name_pulled into the list final_names and append them through the for loop. will this work?

def function_two(input): # i need not_found_dict so what should this input be?
  for name, size in not_found_dict.items(): #using the names in not_found_dict
  discard_name_pulled = not_found_dict['reg.name'] # save the names temporarily to discard_name_pulled using on the 'reg.name' from not_found_dict which is essentially the key to the dict
  not_used_names[] = not_used_names.append(discard_name_pulled) # in the same way in function_one, save the names to the list not_used_names and append them through the for loop. Will this construct work?

主要问题是,因为def make返回了两个词典(found_dict和not_found_dict),如何在function_two中正确输入found_dict而在function_two中输入not_found_dict?

1 个答案:

答案 0 :(得分:0)

首先,在每次执行for循环的第一部分中:found_dict = {}not_found_dict = {}清除字典的内容。我不确定这是不是你想要的。

其次,如果你想从函数中返回多个东西,你总是可以将它们作为数组或元组返回,如下所示:

return [found_dict, not_found_dict]

查看this question了解更多信息。

返回数组或元组后,可以将其存储在另一个变量中:

result=make(inputVariable)

这将允许您根据需要使用每个元素。

result[0]
result[1]

您可以将它们输入到您想要的功能中:

def function_one(inputParameter, found_dict):
    #code ....

def function_one(inputParameter, not_found_dict):
    #code ....

function_one(inputVariable, result[0])
function_two(inputVariable, result[1])