如何使用列表推导来模拟sum()?

问题描述 投票:26回答:9

是否可以使用list comprehension模拟sum()之类的东西?

例如 - 我需要计算列表中所有元素的乘积:

list = [1, 2, 3]
product = [magic_here for i in list]

#product is expected to be 6

执行相同的代码:

def product_of(input):
   result = 1
   for i in input:
      result *= i
   return result
python list
9个回答
37
投票

没有; list comprehension生成一个与其输入一样长的列表。您将需要Python的其他功能工具之一(在本例中特别是reduce())将fold序列转换为单个值。


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

在Python 3上,您需要添加此导入:from functools import reduce

Implementation Artifact

在Python中2.5 / 2.6您可以使用vars()['_[1]']来引用当前正在构建的列表理解。这很糟糕,永远不应该使用,但它与你在问题中提到的最接近(使用list comp来模拟产品)。

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

12
投票

列表理解总是创建另一个列表,因此它在组合它们时没有用处(例如,给出一个数字)。此外,除非你是超级偷偷摸摸,否则没有办法在列表理解中进行任务。

我唯一一次看到使用列表推导对sum方法有用的唯一一次是你只想在列表中包含特定值,或者你没有数字列表:

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)

或另一个例子“:

# 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)

超级偷偷摸摸的方式在列表理解中进行任务

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!

......但那太可怕了:)


5
投票

像这样的东西:

>>> a = [1,2,3]
>>> reduce(lambda x, y: x*y, a)
6

4
投票

我用一些使用Python的reduce算子的代码补充了Ignacio Vazquez-Abrams的答案。

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

也可以写成

list_of_numbers = [1, 5, 10, 100]

def sum(x, y):
    return x + y

reduce(sum, list_of_numbers)

额外:Python在内置的sum函数中提供此功能。这是最易读的表达式imo。

list_of_numbers = [1, 5, 10, 100]
sum(list_of_numbers)

4
投票

启动Python 3.8,并引入assignment expressions (PEP 572):=运算符),我们可以在列表推导中使用和递增变量,从而将列表减少为其元素的总和:

total = 0
[total := total + x for x in [1, 2, 3, 4, 5]]
# 15

这个:

  • 将变量total初始化为0
  • 对于每个项目,total通过赋值表达式增加当前的循环项(total := total + x

3
投票
>>> reduce(int.__mul__,[1,2,3])
6

C:\Users\Henry>python -m timeit -s "" "reduce(int.__mul__,range(10000))" 
1000 loops, best of 3: 910 usec per loop

C:\Users\Henry>python -m timeit -s "from operator import mul" "reduce(mul,range(10000))"
1000 loops, best of 3: 399 usec per loop

C:\Users\Henry>

0
投票

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

它应该是如下代码的逻辑。

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
投票

可以通过使用lambda与列表理解来实现因为我们不能在列表理解中赋值,所以我们使用lambda

解:

>>> (lambda number_list, sum=0:[sum for number in number_list for sum in [sum + number]][-1])([1, 2, 3, 4, 5])
>>> 15
© www.soinside.com 2019 - 2024. All rights reserved.