久久久久久久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 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 欧美久久久久久久久中文字幕 | 欧美日在线 | 久久亚洲精品国产精品紫薇 | 国产97在线看 | www.日韩高清 | 人干人操 | 色综网 | 久色| 久久久久国产 | 一区二区手机在线 | 国产女人与拘做受免费视频 | 在线伊人网 | av一区二区三区 | 欧美天天视频 | 97超碰在线播放 | 免费黄色a视频 | 午夜寂寞影院在线观看 | 国产高清视频一区 | 人人人人人爽 | 国产精品日韩一区二区 | 成人动漫一区二区 | 一区二区三区高清 | 99视频在线 | 爱爱视频日本 | 国产精品色av | 国产亚洲精品久久久久久牛牛 | 欧美一级三级在线观看 | 99久久日韩精品免费热麻豆美女 | 99pao成人国产永久免费视频 | 色婷婷综合成人av | 狠狠综合网 | www.色五月.com | 欧美在线观看一区 | 天天草天天 | 久久成人免费视频 | 日韩国产一区二区三区 | 亚洲 欧美 激情 另类 校园 | 成人在线中文字幕 | 久久在线精品 | 日韩精品久久久 | 色噜噜亚洲男人的天堂 |