我有類似這樣的元組的列表:總和元組的列表中的每個值
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?
可能du plicate [Python元素明智的元組操作像sum](http://stackoverflow.com/questions/497885/python-element-wise-tuple-operations-like-sum) –
@CiroSantilli:它不是重複的。你已經鏈接的問題適用於* two *元組。這個關於元組列表*的問題。換位是解決方案的重要組成部分。儘管這兩種情況下的答案几乎都是逐字的。仍然'a,b'元組和'a_list_of_tuples'是不同的(這種差異可能暴露在最有效的解決方案中)。 – jfs