Python No Action on 2nd Statement After 'IF'

一个人想着一个人 提交于 2019-12-25 01:59:38

问题


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.


回答1:


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(...)


来源:https://stackoverflow.com/questions/22407865/python-no-action-on-2nd-statement-after-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!