你的問題本身有點不清楚。無論如何,我只是假設 -
>>> a = []
>>> a.append((1,2,3))
>>> a.append((7,2,4))
>>> a
[(1, 2, 3), (7, 2, 4)] # list of tuples
我假設你可能有興趣獲得列表中的所有元素的總和。如果這是問題,那麼可以分兩步解決。
1)第一步應該是扁平化列表。
2)然後添加列表中的所有元素。
>>> new_list = [y for x in a for y in x] # List comprehension used to flatten the list
[1, 2, 3, 7, 2, 4]
>>> sum(new_list)
19
一個襯墊
>>> sum([y for x in a for y in x])
19
另一個假設,如果你的問題是零下元組的每一個元素逐項列表,然後使用此:
>>> [tuple(map(lambda y: abs(item - y), x)) for x in a]
[(0, 1, 2), (6, 1, 3)] # map function always returns a list so i have used tuple function to convert it into tuple.
如果問題是別的東西,請詳細說明。
PS:Python List comprehension比其他任何東西都好得多。
請注意'sum'是python中的一個內置函數,因此建議您使用不同的名稱,就像我在答案中所做的一樣。 – abyx 2009-11-17 06:59:46
我已將總數更改爲總和,並且發生相同的錯誤。 – 2009-11-17 07:14:55
當然可以。下面的答案解釋了真正的問題。我剛纔說這是一個更好的做法,現在陰影'總和'功能:) – abyx 2009-11-17 07:23:24