遍历命名空间 [英] Iterate through a Namespace
问题描述
我有一个看起来像这样的命名空间:
I have got a namespace looking like this :
命名空间(aTQ =无,bE =无,bEQ =无,b =无,bQ =无,c =无, c = None,cJ = None,d = None,g = None,jR = ['xx','015'],lC = None,l = None)
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)
如何遍历它,以便可以找到并替换"jR"键的"xx"值?
How can I iterate through it so I can find and replace the 'xx' value for the "jR" key in place ?
推荐答案
我不确定您事先知道什么(名称jR
,或者只有一个名称具有not None
值),但是您可以尝试使用vars(),就像__dict__
一样,这是一个以名称空间中的名称为其键的字典.因此,如果字符串'jR'
在某处,
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]
同样,您可以使用namespace.__dict__
而不是vars()
likewise, you can get the same dict using namespace.__dict__
instead of vars()
会将['xx','015']
中的第一个值保留为jR
的唯一值.
will leave you with the first value in ['xx','015']
as the only value for jR
.
为清楚起见,由于vars()
和__dict__
都返回dict,因此您可以按以下方式遍历它们:
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>>
这篇关于遍历命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!