2013-05-19 82 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)