How to emulate sum() using a list comprehension?

后端 未结 11 1803
星月不相逢
星月不相逢 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:57

    >>> from operator import mul
    >>> nums = [1, 2, 3]
    >>> reduce(mul, nums)
    6
    

    On Python 3 you will need to add this import: from functools import reduce

    Implementation Artifact

    In Python 2.5 / 2.6 You could use vars()['_[1]'] to refer to the list comprehension currently under construction. This is horrible and should never be used but it's the closest thing to what you mentioned in the question (using a list comp to emulate a product).

    >>> nums = [1, 2, 3]
    >>> [n * (vars()['_[1]'] or [1])[-1] for n in nums][-1]
    6
    

提交回复
热议问题