![](/img/trans.png)
[英]How do I sum the first value in each tuple in a list of tuples in Python?
[英]How do I sum the first two values in each tuple in a list of tuples in Python?
不幸的是,我搜索了 stackoverflow,但找不到答案或改編類似的代碼。 問題是我有一個元組列表:
tupl = [(5,3,33), (2,5,2), (4,1,7)]
我應該使用列表理解來獲得這個輸出:
[8,7,5]
我寫的代碼有點垃圾,是:
sum_tupl = []
tupl = [(5,3,33), (2,5,2), (4,1,7)]
sum_tupl = [tupl[0][0]+tupl[0][1] for tuple in tupl]
sum_tupl
但它沒有做我想做的事,而是返回
[8,8,8]
這是執行 3 次的第一對夫婦的總和。 我嘗試使用一個變體:
tupl = [(5,3,33), (2,5,2), (4,1,7)]
sum_tupl = [sum(tupl[0],tupl[1]) for tuple in tupl]
sum_tupl
(缺少一些東西)但無濟於事。
注意:當您開始使用 python 時,使用循環而不是列表推導式要容易得多,因為這樣您可以更輕松地 調試代碼,無論是使用print()
語句還是使用調試器單步調試。
現在,進入答案:
當你for x in y
做一個列表y
,單個項目進入x
。 因此, for tuple in tupl
代碼,您不應該使用tupl
因為那是整個 list 。 您需要使用列表中的單個項目,即tuple
。
請注意,命名變量tuple
不是一個好主意,因為它已經是 python 中的內置類型。
你需要:
tupl = [(5,3,33), (2,5,2), (4,1,7)]
sum_tupl = [t[0]+t[1] for t in tupl]
這給出了列表
sum_tupl: [8, 7, 5]
如果您有更多要求和的元素,使用sum()
函數和t
的切片而不是寫出所有內容更有意義。 例如,如果你想對前 5 個元素求和,你會寫
sum_tupl = [sum(t[0:5]) for t in tupl]
代替
sum_tupl = [t[0]+t[1]+t[2]+t[3]+t[4] for t in tupl]
每次循環迭代都在訪問tupl
列表的第一個元素,而不是使用當前元素。 這就是你想要的:
sum_tupl = [t[0] + t[1] for t in tupl]
我更喜歡切片:
>>> [x + y for x, y, *_ in tupl]
[8, 7, 5]
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.