How to emulate sum() using a list comprehension?

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

    No; a list comprehension produces a list that is just as long as its input. You will need one of Python's other functional tools (specifically reduce() in this case) to fold the sequence into a single value.

    0 讨论(0)
  • 2020-12-05 13:51

    List comprehension always creates another list, so it's not useful in combining them (e.g. to give a single number). Also, there's no way to make an assignment in list comprehension, unless you're super sneaky.

    The only time I'd ever see using list comprehensions as being useful for a sum method is if you only want to include specific values in the list, or you don't have a list of numbers:

    list = [1,2,3,4,5]
    product = [i for i in list if i % 2 ==0] # only sum even numbers in the list
    print sum(product)
    

    or another example":

    # list of the cost of fruits in pence
    list = [("apple", 55), ("orange", 60), ("pineapple", 140), ("lemon", 80)]
    product = [price for fruit, price in list]
    print sum(product)
    

    Super sneaky way to make an assignment in a list comprehension

    dict = {"val":0}
    list = [1, 2, 3]
    product = [dict.update({"val" : dict["val"]*i}) for i in list]
    print dict["val"] # it'll give you 6!
    

    ...but that's horrible :)

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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])
    
    0 讨论(0)
  • 2020-12-05 13:58

    Something like this should suffice:

    list = [1, 2, 3]
    product = product_of([i for i in list])  
    
    0 讨论(0)
  • 2020-12-05 14:01

    I complement the answer of Ignacio Vazquez-Abrams with some code that uses the reduce operator of Python.

    list_of_numbers = [1, 5, 10, 100]
    reduce(lambda x, y: x + y, list_of_numbers)
    

    which can also be written as

    list_of_numbers = [1, 5, 10, 100]
    
    def sum(x, y):
        return x + y
    
    reduce(sum, list_of_numbers)
    

    Bonus: Python provides this functionality in the built-in sum function. This is the most readable expression imo.

    list_of_numbers = [1, 5, 10, 100]
    sum(list_of_numbers)
    
    0 讨论(0)
提交回复
热议问题