python list comprehension to produce two values in one iteration

后端 未结 12 2140
刺人心
刺人心 2021-02-03 17:20

I want to generate a list in python as follows -

[1, 1, 2, 4, 3, 9, 4, 16, 5, 25 .....]

You would have figured out, it is nothing but n,

12条回答
  •  不要未来只要你来
    2021-02-03 17:53

    You can create a list of lists then use reduce to join them.

    print [[n,n*n] for n in range (10)]
    

    [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

    print reduce(lambda x1,x2:x1+x2,[[n,n*n] for n in range (10)])
    

    [0, 0, 1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]

     print reduce(lambda x1,x2:x1+x2,[[n**e for e in range(1,4)]\
     for n in range (1,10)])
    

    [1, 1, 1, 2, 4, 8, 3, 9, 27, 4, 16, 64, 5, 25, 125, 6, 36, 216, 7, 49, 343, 8, 64, 512, 9, 81, 729]

    Reduce takes a callable expression that takes two arguments and processes a sequence by starting with the first two items. The result of the last expression is then used as the first item in subsequent calls. In this case each list is added one after another to the first list in the list of lists and then that list is returned as a result.

    List comprehensions implicitly call map with a lambda expression using the variable and sequence defined by the "for var in sequence" expression. The following is the same sort of thing.

    map(lambda n:[n,n*n],range(1,10))
    

    [[1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

    I am unaware of a more natural python expression for reduce.

提交回复
热议问题