问题描述
我试图遍历字典并在每个键上调用一个函数.
I am trying to loop over a dictionary and call a function on each key.
如果该函数没有为该键返回 None
项,则我希望将输出附加到列表中,并且我也希望将该键附加到第二个列表中.
If the function does not return None
entry for that key, I want the output to be appended to a list and I also want that key to be appended to a second list.
这是我的代码:
output_list = []
key_list =[]
for i in dict.keys():
if obj.method(i):
output_list.append(obj.method(i))
key_list.append(i)
return output_list
return key_list
但是,由于某种原因,第二个列表 key_list
却从未填充过-您不能在 if
下方有两个以上的语句吗?
However, for some reason the second list, key_list
, is never populated - can you not have two statements below an if
like the above?
执行此操作的原因是,我希望最终产生一个输出,在该输出中,只要输出不是 None
,就将dict的每个键与它的关联函数ouput一起列出.
The reason that I am doing this is that I want to eventually produce an output where each key of the dict is listed alongside it's associated function ouput, whenever the output is not None
.
推荐答案
key_list
正在填充,但是您只能从函数中返回一次.
key_list
is being populated, however you can only return once from a function.
尽管可以返回多个变量,但是您可以返回结果的元组.更改:
You can return a tuple of results though to return multiple variables. Change:
return output_list
return key_list
到
return output_list, key_list
在调用代码中执行:
output_list, key_list = my_function(...)
这篇关于在' IF'之后的第二条语句上,Python无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!