How to emulate sum() using a list comprehension?

后端 未结 11 1800
星月不相逢
星月不相逢 2020-12-05 13:24

Is it possible to emulate something like sum() using list comprehension ?

For example - I need to calculate the product of all elements in a list :

l         


        
11条回答
  •  日久生厌
    2020-12-05 13:58

    Found the magic on http://code.activestate.com/recipes/436482/.

    >>> L=[2, 3, 4]
    >>> [j for j in [1] for i in L for j in [j*i]][-1]
    24
    

    It should be the logic like the following code.

    L=[2, 3, 4]
    P=[]
    for j in [1]:
        for i in L:
            for j in [j*i]:
                P.append(j)
    print(P[-1])
    

提交回复
热议问题