在Python dict中重用函数结果

Kar*_*ode 3 python python-2.7

我有以下(非常简化)的词典.该get_details函数是一个API调用,我想避免做两次.

ret = { 
    'a': a,
    'b': [{
        'c': item.c,
        'e': item.get_details()[0].e,
        'h': [func_h(detail) for detail in item.get_details()],
    } for item in items]
}
Run Code Online (Sandbox Code Playgroud)

我当然可以像这样重写代码:

b = []
for item in items:
    details = item.get_details()
    b.append({
        'c': item.c,
        'e': details[0].e,
        'h': [func_h(detail) for detail in details],
    })

ret = { 
    'a': a,
    'b': b
}
Run Code Online (Sandbox Code Playgroud)

但是想要使用第一种方法,因为它看起来更像pythonic.

khe*_*ood 6

您可以使用中间生成器从项目中提取详细信息.像这样的东西:

ret = { 
    'a': a,
    'b': [{
        'c': item.c,
        'e': details[0].e,
        'h': [func_h(detail) for detail in details],
    } for (item, details) in ((item, item.get_details()) for item in items)]
}
Run Code Online (Sandbox Code Playgroud)