2013-01-06 47 views
20

我有類似這樣的元組的列表:總和元組的列表中的每個值

l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)] 

我想創建一個簡單的一行,這將使我以下結果:

r = (25, 20) or r = [25, 20] # don't care if tuple or list. 

這將是喜歡做如下:

r = [0, 0] 
for t in l: 
    r[0]+=t[0] 
    r[1]+=t[1] 

我相信這是很簡單的東西,但我不能把它。

注:我看了一下類似的問題已經:

How do I sum the first value in a set of lists within a tuple?

How do I sum the first value in each tuple in a list of tuples in Python?

+0

可能du plicate [Python元素明智的元組操作像sum](http://stackoverflow.com/questions/497885/python-element-wise-tuple-operations-like-sum) –

+0

@CiroSantilli:它不是重複的。你已經鏈接的問題適用於* two *元組。這個關於元組列表*的問題。換位是解決方案的重要組成部分。儘管這兩種情況下的答案几乎都是逐字的。仍然'a,b'元組和'a_list_of_tuples'是不同的(這種差異可能暴露在最有效的解決方案中)。 – jfs

回答

46

使用zip()sum()

In [1]: l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)] 

In [2]: [sum(x) for x in zip(*l)] 
Out[2]: [25, 20] 

或:

In [4]: map(sum, zip(*l)) 
Out[4]: [25, 20] 

timeit結果:

In [16]: l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]*1000 

In [17]: %timeit [sum(x) for x in zip(*l)] 
1000 loops, best of 3: 1.46 ms per loop 

In [18]: %timeit [sum(x) for x in izip(*l)]  #prefer itertools.izip 
1000 loops, best of 3: 1.28 ms per loop 

In [19]: %timeit map(sum, zip(*l)) 
100 loops, best of 3: 1.48 ms per loop 

In [20]: %timeit map(sum, izip(*l))    #prefer itertools.izip 
1000 loops, best of 3: 1.29 ms per loop 
+0

O_O簡直不敢相信那是多麼的簡單,我怎麼會忘記'zip'?謝謝。哪個更有效率? 'map'或'list-comprehension'方法? –

+0

@Inbar測試並找出答案。 – Triptych

+1

與內置函數一起使用時,'map'有時會優於'list comprehension'。 –

2

我要的東西添加到給定答案:

如果我的字典例如數組

l = [{'quantity': 10, 'price': 5},{'quantity': 6, 'price': 15},{'quantity': 2, 'price': 3},{'quantity': 100, 'price': 2}] 

我想獲得兩個(或更多)的計算量的總和,例如,數量和價格*數量的總和

我可以這樣做:

(total_quantity, total_price) = (
sum(x) for x in zip(*((item['quantity'], 
         item['price'] * item['quantity']) 
         for item in l))) 

相反的:

total_quantity = 0 
total_price = 0 
for item in l: 
    total_quantity += item['quantity'] 
    total_price += item['price'] * item['quantity'] 

也許第一個解決方案是不太可讀,但更 「pythonesque」 :)

+1

這對Ashwini的答案有什麼影響?這個問題不是關於你是對的 –

+1

的列表,但它增加了一些關於在複雜操作中使用sum和zip的內容。我正在尋找這樣的事情,我找到了這個答案,我用它來解決我自己的問題,這個問題是關於詞典的。因此,我認爲將我的解決方案與可能有同樣問題的其他人分享是很好的做法。 –

1

不使用拉鍊

sum(e[0] for e in l), sum(e[1] for e in l) 
相關問題