Python在'IF'之后的第二条语句上不执行任何操作 [英] Python No Action on 2nd Statement After 'IF'
问题描述
我试图遍历字典并在每个键上调用一个函数.
如果该函数没有为该键返回None
条目,则我希望将输出附加到列表中,并且我也希望将该键附加到第二个列表中.
这是我的代码:
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
之下有两个语句吗?
执行此操作的原因是,我希望最终产生一个输出,在该输出中,只要输出不是None
,该dict的每个键都将与它的关联函数ouput一起列出.
key_list
正在填充,但是您只能从函数中返回一次.
尽管可以返回多个变量,但是您可以返回结果的元组.更改:
return output_list
return key_list
到
return output_list, key_list
在调用代码中执行:
output_list, key_list = my_function(...)
I am trying to loop over a dictionary and call a function on each key.
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.
Here is my code:
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
However, for some reason the second list, key_list
, is never populated - can you not have two statements below an if
like the above?
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
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
to
return output_list, key_list
And in the calling code do:
output_list, key_list = my_function(...)
这篇关于Python在'IF'之后的第二条语句上不执行任何操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!