字符串/dict/列表索引的短名称



在python中,我似乎需要经常在dicts/lists中创建dicts/lists/lists/dicts/lists,然后在复杂的if/elif/else树中访问这些结构。有没有什么方法可以让我用简写的方式访问这个数据结构的某个级别,使代码更加简洁。

这是一个示例代码行:

schema[exp][node]['properties']['date'] = i.partition('(')[2].rpartition(')')[0].strip()

后面是一整堆以"schema[exp][node]['properties']['fo']"开头的其他行我想要的是:

reference_maker(schema[exp][node]['properties']['date'], schema_props)
schema_props['date'] = i.partition('(')[2].rpartition(')')[0].strip()

但我甚至想不出从哪里开始。

如果你不担心它会改变:

schema_props = schema[exp][node]['properties']
schema_props['date'] = ...

但如果你想让参考资料挂起并自动更新:

schema_props = lambda: schema[exp][node]['properties']
schema_props()['date'] = ...
node = node + 1
# this now uses the next node
schema_props()['date'] = ...

或者不带lambda:

def schema_props():
    return schema[exp][node]['properties']
schema_props()['date'] = ...
node = node + 1
# this now uses the next node
schema_props()['date'] = .

不确定我是否理解,但以下内容有什么问题?

schema_props = schema[exp][node]['properties']
schema_props['date'] = i.partition('(')[2].rpartition(')')[0].strip()

当然,你必须小心,schema_props总是指向你的dict中仍然有效的条目。即,一旦你手动重置schema[exp][node]['properties'],你的schema_props引用将不再更新原始dict。

对于更详细的间接处理,您可以构建自己的集合类型,然后这些集合类型可能始终保留对基dict的引用。(另请参阅:http://docs.python.org/2/library/collections.html#collections-抽象基类)

最新更新