python风格指南pep8。多行多列di

2024-04-19 03:37:08 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,当我有一个多维字典,我想使用它,我访问它与一些较长的名字,我遇到一些+80字符行。我怎样才能根据pep8缩短这个时间呢。在

例如:

myvalue = mydict[application_module][chapter][paragraph][line][character][some_other_value]

问题:如何在不重命名变量的情况下缩短/多行?在

我知道我可以:

^{pr2}$

使用\ for muliline是唯一的解决方案吗?在


Tags: 字典applicationline时间some名字字符mydict
1条回答
网友
1楼 · 发布于 2024-04-19 03:37:08

是的,为了拒绝引发语法错误,您需要对新行进行转义。但作为另一种替代方法,您可以使用递归函数从嵌套字典中获取值:

>>> 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内的生成器表达式:

^{pr2}$

或者,作为一种更为python的方法,您可以将键的迭代器传递给函数:

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

相关问题 更多 >