How to emulate sum() using a list comprehension?

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

提交回复
热议问题