Python 如何使用列表理解来模拟 sum()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16632124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:12:54  来源:igfitidea点击:

How to emulate sum() using a list comprehension?

pythonlist

提问by StKiller

Is it possible to emulate something like sum() using list comprehension?

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

For example - I need to calculate the product of all elements in a list :

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

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

#product is expected to be 6

Code that is doing the same :

执行相同操作的代码:

def product_of(input):
   result = 1
   for i in input:
      result *= i
   return result

采纳答案by Ignacio Vazquez-Abrams

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 foldthe sequence into a single value.

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

回答by jamylak

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

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

Implementation Artifact

实现工件

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

在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

回答by Patrick

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:

我曾经看到使用列表推导式对 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)

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

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

回答by HennyH

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

回答by Yarkee

Something like this:

像这样的东西:

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

回答by jam

Found the magic on http://code.activestate.com/recipes/436482/.

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

回答by Drizzt

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

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

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 sumfunction. This is the most readable expression imo.

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

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

回答by Gowtham MS

It is possible to achieve by using lambda with list comprehension Since we can't assign a value in list comprehension we go with lambda

可以通过将 lambda 与列表推导结合使用来实现由于我们无法在列表推导中赋值,所以我们使用 lambda

Solution:

解决方案:

>>> (lambda number_list, sum=0:[sum for number in number_list for sum in [sum + number]][-1])([1, 2, 3, 4, 5])
>>> 15

回答by Xavier Guihot

Starting Python 3.8, and the introduction of assignment expressions (PEP 572)(:=operator), we can use and increment a variable within a list comprehension and thus reduce a list to the sum of its elements:

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

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

This:

这个:

  • Initializes a variable totalto 0
  • For each item, totalis incremented by the current looped item (total := total + x) via an assignment expression
  • 将变量初始化total0
  • 对于每个项目,通过赋值表达式total由当前循环项目 ( total := total + x)递增

回答by Crowton

I might be a bit late for this discussion, but I would like to mention that list comprehentions are turing complete, and thus this can be done with a list comprehention!

我的讨论可能有点晚了,但我想提一下,列表理解是图灵完备的,因此这可以通过列表理解来完成!

This however is messy, so I have used the following trick, which makes a cummulative array, and returns the last element

然而,这很混乱,所以我使用了以下技巧,它创建了一个累积数组,并返回最后一个元素

def sum(l):
    return [c[-1] for c in [[0]] for e in l if c.append(c[-1] + e) is None][-1]