久久久久久久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 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 亚洲精品国产a久久久久久 午夜影院网站 | 日本一区二区三区在线观看 | 日韩在线精品视频 | 粉嫩高清一区二区三区 | 日日骑 | 精品日韩 | 国产 日韩 欧美 中文 在线播放 | 999视频在线播放 | 亚洲福利一区二区 | 日韩欧美在线观看 | 在线观看国产91 | 国产视频三级 | 在线免费91 | 日韩中文在线观看 | 四虎影视免费观看 | 国产精品av久久久久久毛片 | av网站在线播放 | 欧美日韩在线一区二区三区 | 国产成人高清视频 | 羞羞视频网站在线观看 | 99热精品在线观看 | 天天干视频网 | 伊人欧美视频 | 亚洲精品中文在线观看 | 久热精品免费 | 91精品国产91久久久久久吃药 | 性一交一乱一伦视频免费观看 | 日韩2020狼一二三 | 中文字幕在线网 | 青青草视频免费观看 | aaa级片 | 草草视频在线免费观看 | 国产免费一区二区三区 | 久久国产精品视频 | 国产 欧美 日韩 一区 | 日韩精品一区二区久久 | 日本aaaa | 欧美电影大全 | 一起操网站 | 美女视频久久 | 在线午夜 |