小编Kar*_*ode的帖子

在Python dict中重用函数结果

我有以下(非常简化)的词典.该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.

python python-2.7

3
推荐指数
1
解决办法
86
查看次数

标签 统计

python ×1

python-2.7 ×1