久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

嵌套列表中第一個值的總和

sum of first value in nested list(嵌套列表中第一個值的總和)
本文介紹了嵌套列表中第一個值的總和的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

在傳統的python中,sum函數給出一個list的總和:

In traditional python, the sum function gives the sum of a list:

sum([0,1,2,3,4])=10

另一方面,如果你有一個嵌套列表怎么辦:

On the other hand, what if you have a nested list as so:

sum([[1,2,3],[4,5,6],[7,8,9]])

我們發現錯誤:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'

除此之外,我們如何在嵌套列表中找到第一個值(索引 0)的 sum?如:

In addition to this, how could we find the sum of the first values (index 0) in a nested list? Such as:

something([[1,2,3],[4,5,6],[7,8,9]])=12

推薦答案

要獲得所有第一個元素的總和,您需要有一個生成器表達式

To get the sum of all the first elements you need to have a generator expression

>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> sum(i[0] for i in a)
12

您得到 unsupported operand type(s) for +: 'int' and 'list' 因為您嘗試添加三個列表,這不是所需的行為.

You are getting unsupported operand type(s) for +: 'int' and 'list' because you are trying to add the three lists which is not the desired behavior.

如果您想要一個第一個元素的列表,然后找到它們的總和,您可以嘗試使用列表推導

If you want a list of first elements and then find their sum, you can try a list comprehension instead

>>> l = [i[0] for i in a]
>>> l
[1, 4, 7]
>>> sum(l)
12

或者您可以調用 __next__ 方法,因為列表是可迭代的(如果 Py3)

Or you can call the __next__ method as list is an iterable (If Py3)

>>> sum(zip(*a).__next__())
12

這篇關于嵌套列表中第一個值的總和的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區域周圍繪制一個矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個矩形邊界框中應用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 欧美激情综合 | 春色av | 麻豆视频在线免费看 | 99精品国产一区二区青青牛奶 | 欧美视频一区二区三区 | 一级a毛片 | 日韩久久久久久 | 一区二区三区四区不卡视频 | av一区二区三区四区 | 久久伊人精品 | 亚洲一区二区三区在线 | 成年人在线观看视频 | 全免费a级毛片免费看视频免 | 精品国产一区二区在线 | 亚洲精品久久久久久国产精华液 | 欧美国产精品一区二区三区 | 丝袜美腿一区二区三区 | 97超碰人人 | 午夜噜噜噜 | 国产精品自拍av | 国产精品国产精品国产专区不卡 | 亚洲国产精品久久久久秋霞不卡 | 97精品一区二区 | 电影在线| 91中文视频 | 亚洲精品免费观看 | 欧美一区二区在线 | 久久精品国产免费 | 特级生活片 | www.亚洲一区 | 一级a毛片 | 中文字幕黄色大片 | 99国产精品久久久久久久 | 人人叉| 精品国产一区二区三区久久久四川 | 二区久久 | 成人福利电影 | 欧美日韩国产在线观看 | 欧美日韩国产在线 | 9色视频在线 | 91av大全|