How to emulate sum() using a list comprehension?

后端 未结 11 1806
星月不相逢
星月不相逢 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 14:06

    I might be a bit late for this discussion, but I would like to mention that list comprehentions are turing complete, and thus this can be done with a list comprehention!

    This however is messy, so I have used the following trick, which makes a cummulative array, and returns the last element

    def sum(l):
        return [c[-1] for c in [[0]] for e in l if c.append(c[-1] + e) is None][-1]
    

提交回复
热议问题