Iterate through a Namespace

点点圈 提交于 2020-01-01 08:06:50

问题


I have got a namespace looking like this :

Namespace(aTQ=None, bE=None, bEQ=None, b=None, bQ=None, c=None, c=None, cJ=None, d=None, g=None, jR=['xx', '015'], lC=None, l=None)

How can I iterate through it so I can find and replace the 'xx' value for the "jR" key in place ?


回答1:


I'm not sure what you know in advance, (the name jR, or only that one name has a not None value) but you can try using vars() which, like __dict__ should be a dict that has the names in your namespace as its keys. So if you have the string 'jR' somewhere,

vars()['jR'] = vars()['jR'][0]

likewise, you can get the same dict using namespace.__dict__ instead of vars()

will leave you with the first value in ['xx','015'] as the only value for jR.

EDIT: To be clear, since vars() and __dict__ both return dicts, you can iterate through them as:

for k in namespace.__dict__:
    if namespace.__dict__[k] is not None:
        <<do something>>


来源:https://stackoverflow.com/questions/14865961/iterate-through-a-namespace

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