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

當列表的長度未知時,將 Python 列表中的前 2 個元

Summing first 2 elements in a Python list when the length of the list is unknown(當列表的長度未知時,將 Python 列表中的前 2 個元素求和)
本文介紹了當列表的長度未知時,將 Python 列表中的前 2 個元素求和的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在從 codingbat.com 進行以下 Python 列表練習:

I am working on the following Python list exercise from codingbat.com:

給定一個整數數組,返回數組中前兩個元素的和大批.如果數組長度小于2,只需將元素相加即可存在,如果數組長度為 0,則返回 0.示例:

Given an array of ints, return the sum of the first 2 elements in the array. If the array length is less than 2, just sum up the elements that exist, returning 0 if the array is length 0. Examples:

sum2([1, 2, 3]) → 3 

sum2([1, 1]) → 2

sum2([1, 1, 1, 1]) → 2

我的解決方案如下:

def sum2(nums):
  if len(nums)>=2:
    return nums[0] + nums[1]
  elif len(nums)==1:
    return nums[0]
  return 0

但我想知道有沒有什么辦法可以用更少的條件語句來解決這個問題.

But I wonder if there's any way to solve the problem with fewer conditional statements.

推薦答案

有.解決方案的兩個要素 - 內置函數 sum 和列表的 切片:

There is. Two elements of the solution - builtin function sum and lists's slices:

>>> sum([1,2,3][:2])
3
>>> sum([1,1,1,1][:2])
2
>>> sum([1,1][:2])
2
>>> sum([1][:2])
1
>>> sum([][:2])
0

這篇關于當列表的長度未知時,將 Python 列表中的前 2 個元素求和的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持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 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 国产粉嫩尤物极品99综合精品 | 欧美高清视频在线观看 | 亚洲国产精品人人爽夜夜爽 | 免费天天干 | 亚洲国产伊人 | 天天色图 | 国产精品一二三区在线观看 | 欧美一级黑人aaaaaaa做受 | 国产高清在线精品 | 一级大片免费 | 综合色在线| 亚洲精品一区二三区不卡 | 国产aⅴ精品 | 天堂一区二区三区 | 午夜精品视频一区 | 精品视频一区二区 | 毛片网站在线观看 | 看a网站 | 一区二区三区四区av | 国产成人免费 | 99久久久久| 亚洲一区中文字幕 | 精品国产视频 | 在线观看视频一区二区三区 | 久久久精彩视频 | 欧美国产精品久久久 | 九九热re| 欧美成人一区二免费视频软件 | 国产小视频在线看 | 国产黄色在线 | 国产精品区二区三区日本 | 日韩国产专区 | 2018国产大陆天天弄 | 亚洲精久久久 | 成年人在线观看视频 | 亚洲高清一区二区三区 | 国产在线激情视频 | 在线成人av| 亚洲成人免费视频 | 久草视频在线播放 | 亚洲精品区 |