How to reuse an expression in a comprehension expression?

后端 未结 2 1136
孤街浪徒
孤街浪徒 2020-12-07 04:49

Imagine a theoretical snippet:

# just for this example: `bad_structure` contains a list of dicts with different keys
# for the same semantic
bad_structure =          


        
2条回答
  •  孤城傲影
    2020-12-07 05:25

    Yes! Python 3.8 introduces the "Assignment operator" :=, which allows you to define a variable within the local scope of a single expression (e.g. a comprehension). In your example, you would do this:

    result = {(p := next(k for k in ('path', 'subdir') if k in e)): some_func(p) 
              for e in bad_structure}
    

    Disclaimer: this will not work in any version of python before 3.8.

提交回复
热议问题