List comprehension: Returning two (or more) items for each item

前端 未结 6 890
庸人自扰
庸人自扰 2020-12-02 16:14

Is it possible to return 2 (or more) items for each item in a list comprehension?

What I want (example):

[f(x), g(x) for x in range(         


        
6条回答
  •  余生分开走
    2020-12-02 16:58

    A solution using reduce:

    from functools import reduce
    
    f    = lambda x: f"f({x})" ## Just for example
    g    = lambda x: f"g({x})"
    data = [1, 2, 3]
    
    reduce(lambda acc, x: acc + [f(x), g(x)], data, [])
    # => ['f(1)', 'g(1)', 'f(2)', 'g(2)', 'f(3)', 'g(3)']
    

    While not a list comprehension, this is a functional way of approaching the problem. A list comprehension is essentially another way of maping over data, but in this case where the mapping isn't one to one between the input and the output, reduce allows some wiggle room with how the output can be generated.

    In general, any for implementation of the form:

    result = []
    for n in some_data:
      result += some_operation()
      ## etc.
    

    (I.e. for loops intended to produce a side effect on a list or similar data structure)

    Can be refactored into a declarative map/reduce/filter implementation.

提交回复
热议问题