2013-05-19 88 views
19

是否可以使用list comprehension来模拟类似sum()的事情?Python - 使用列表理解模拟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 
+0

可能重复[像sum()那样的Python函数,但用于乘法?产品()?](http://stackoverflow.com/questions/595374/whats-the-python-function-like-sum-but-for-multiplication-product) –

回答

29

不;列表理解产生与其输入一样长的列表。您将需要Python的其他功能工具之一(在这种情况下,特别是reduce())将fold序列转换为单个值。

+3

谢谢你的第一句话。这是我正在寻找的答案。在Python 3中为 – StKiller

+0

它是[functools](https://docs.python.org/3/library/functools.html)模块 – xealits

37
>>> 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]']来引用当前正在构建的列表理解。这是可怕和应该从来没有被使用,但它是最接近你提到的问题(使用列表比较模拟产品)。

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

egads,这只是...我不事件知道。 – joneshf

+2

多数民众赞成在实际上有点整洁...我不知道你可以做到这一点(并没有什么时候或为什么你会想要的想法)...但一切都相同 –

+1

+1为你的结果偷偷摸摸的方法得到结果我;-) – Patrick

9

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

我曾经看到使用列表理解为有用的方法和唯一的一次是,如果你只是想在列表中包含特定的值,或者你没有号码的清单:

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! 

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

+0

+1提到最后一种方法也很糟糕:) – jamylak

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

事情是这样的:

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

我认为你的意思是x + y不是x * y ...尽管两者的测试数据都是相同的结果 –

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

这被标记为VLQ。构建一个完整的列表,然后只取一个值 - 效率非常低,并且在技术上不“用列表理解来模拟”(这对于最佳答案中所述的原因是不可能的)。这可以作为一个“反例”,但它是如此糟糕,我倾向于建议删除。 –

3

我补充伊格纳西奥巴斯克斯 - 艾布拉姆斯的答案与使用reduce操作的Python的一些代码。

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功能。这是最可读的表达式。

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