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

StK*_*ler 28 python list

是否可以使用列表理解来模拟sum()之类的东西?

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

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

#product is expected to be 6
Run Code Online (Sandbox Code Playgroud)

执行相同的代码:

def product_of(input):
   result = 1
   for i in input:
      result *= i
   return result
Run Code Online (Sandbox Code Playgroud)

jam*_*lak 40

>>> from operator import mul
>>> nums = [1, 2, 3]
>>> reduce(mul, nums)
6
Run Code Online (Sandbox Code Playgroud)

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

实现工件

在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
Run Code Online (Sandbox Code Playgroud)

  • egads,那只是...我不知道事件. (3认同)
  • 多数民众赞成有点整洁......我不知道你能做到这一点(并且没有想法何时或为什么你会想要)...但是所有的一切都很酷 (2认同)

Ign*_*ams 38

没有; list comprehension生成一个与其输入一样长的列表.您将需要Python的其他功能工具之一(特别是reduce()在这种情况下)将序列折叠为单个值.

  • 谢谢你的第一句话.这是我正在寻找的答案. (3认同)
  • 在Python 3中,它是[functools](https://docs.python.org/3/library/functools.html)模块 (2认同)

Pat*_*ick 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)
Run Code Online (Sandbox Code Playgroud)

或另一个例子":

# 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)
Run Code Online (Sandbox Code Playgroud)

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

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!
Run Code Online (Sandbox Code Playgroud)

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


Yar*_*kee 6

像这样:

>>> a = [1,2,3]
>>> reduce(lambda x, y: x*y, a)
6
Run Code Online (Sandbox Code Playgroud)

  • 我认为您的意思是x + y而不是x * y ...尽管两者都为您的测试数据提供了相同的结果 (2认同)

Xav*_*hot 6

从开始Python 3.8,并引入赋值表达式(PEP 572):=运算符),我们可以在列表推导中使用和增加变量,从而将列表简化为其元素的总和:

total = 0
[total := total + x for x in [1, 2, 3, 4, 5]]
# 15
Run Code Online (Sandbox Code Playgroud)

这个:

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

  • [total :=total + x for x in [1, 2, 3, 4, 5]][-1] 将给出总和 (15)。您需要结果的最后一个元素。 (4认同)

Dri*_*zzt 5

我用一些使用reducePython运算符的代码来补充Ignacio Vazquez-Abrams的答案。

list_of_numbers = [1, 5, 10, 100]
reduce(lambda x, y: x + y, list_of_numbers)
Run Code Online (Sandbox Code Playgroud)

也可以写成

list_of_numbers = [1, 5, 10, 100]

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

reduce(sum, list_of_numbers)
Run Code Online (Sandbox Code Playgroud)

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

list_of_numbers = [1, 5, 10, 100]
sum(list_of_numbers)
Run Code Online (Sandbox Code Playgroud)