How to reuse an expression in a comprehension expression?

后端 未结 2 1132
孤街浪徒
孤街浪徒 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条回答
  •  -上瘾入骨i
    2020-12-07 05:38

    You can use an intermediate comprehension to bind to a name:

    result = {
        p: some_func(p)
        # bind intermediate result to p
        for p in (  # nested comprehension to produce intermediate result
            next(k for k in ('path', 'subdir') if k in e)
            for e in bad_structure
        )
     }
    

    Instead of mapping directly to two separate expressions, it first maps to a common expression which then is mapped to two separate expressions.

    You can pass along and rename an arbitrary number of values. Create a tuple in the inner comprehension, and unpack it to multiple names in the outer comprehension.

    result = {
        p: some_func(e, p)
        for e, p in (
            (e, next(iter(e)))
            for e in bad_structure
        )
     }
    

提交回复
热议问题