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

前端 未结 6 884
庸人自扰
庸人自扰 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:59

    This lambda function zips two lists into a single one:

    zipped = lambda L1, L2: [L[i] 
                             for i in range(min(len(L1), len(L2))) 
                             for L in (L1, L2)]
    

    Example:

    >>> f = [x for x in range(5)]
    >>> g = [x*10 for x in range(5)]
    >>> zipped(f, g)
    [0, 0, 1, 10, 2, 20, 3, 30, 4, 40]
    

提交回复
热议问题