你好,当我有一个我想使用的多维字典时,我用一些较长名称的变量访问它,我遇到了一些 +80 字符行。我怎样才能根据 pep8 缩短它。
例如:
myvalue = mydict[application_module][chapter][paragraph][line][character][some_other_value]
问题:如何在不重命名变量的情况下将其缩短/多行化?
我知道我能做到:
myvalue = mydict[application_module] \
[chapter] \
[paragraph] \
[line] \
[some_other_value]
将\用于 muliline 是唯一的解决方案吗?
最佳答案
是的,为了拒绝引发语法错误,您需要转义新行。但作为另一种替代方法,您可以使用递归函数从嵌套字典中获取值:
>>> d = {1: {2: {3: {4: {5: 'a'}}}}}
>>> def get_item(d,*keys):
... for i,j in enumerate(keys):
... item = d[j]
... if isinstance(item, dict):
... return get_item(item,*keys[i+1:])
... return item
或者在 next
中使用生成器表达式:
>>> def get_item(d,*keys):
... return next(get_item(d[j],*keys[i+1:]) if isinstance(d[j],dict) else d[j] for i,j in enumerate(keys))
...
>>> print get_item(d,1,2,3,4,5)
a
或者作为一种更 pythonic 的方式,您可以将键的迭代器传递给您的函数:
def get_item(d,keys):
try:
item = d[next(keys)]
except KeyError:
raise Exception("There is a mismatch within your keys")
if isinstance(item, dict):
return get_item(item,keys)
return item
关于python 样式指南 pep 8。多行多列字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34696045/