久久久久久久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 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 亚洲男女激情 | 国产黄色网址在线观看 | 国产视频福利一区 | 欧美成年网站 | 国产一区二区麻豆 | 日韩视频在线观看中文字幕 | 国产一区在线免费 | 国产精品爱久久久久久久 | 天天操网 | 欧美a区 | 亚洲高清视频在线观看 | 玖玖色在线视频 | 中文无吗| 波多野结衣在线观看一区二区三区 | 久久精品中文 | 激情五月婷婷丁香 | 一区二区国产在线观看 | 久久福利电影 | 精品一区二区电影 | 日日草夜夜草 | 欧美在线视频a | 国产成人精品久久二区二区91 | 午夜爽爽爽男女免费观看 | 欧美一区二区大片 | 91色网站 | 日韩国产一区二区三区 | 亚洲视频免费播放 | 免费性视频 | 黄色毛片在线观看 | 国产精品九九视频 | 久草视频2 | 国产精品久久精品 | 国产在线视频一区 | 99av成人精品国语自产拍 | 亚洲高清在线免费观看 | 理论片87福利理论电影 | 免费视频一区二区 | 一级片免费视频 | 小h片免费观看久久久久 | 婷婷丁香综合网 | 蜜桃精品在线 |