本文介紹了當列表的長度未知時,將 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模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!