添加列表python的特定元素

2024-05-14 12:51:51 发布

您现在位置:Python中文网/ 问答频道 /正文

“pyschool”练习:

"Define a function calls addFirstAndLast(x) that takes in a list of numbers and returns the sum of the first and last numbers."

这是我想出的最好的解决办法。有没有更优雅的方法来编写这个只使用内置函数的函数?在

def addFirstAndLast(x):
    sum_list = []
    if len(x) == 0:
        return 0
    elif len(x) == 1 :
        return int(x[0])
    elif len(x) > 1 :
        sum_list.append(x[0]) 
        sum_list.append(x[-1])
    return sum(sum_list)

Tags: andofthe函数lenreturnfunctionlist
3条回答
>>> def addFirstAndLast(x):
...   return (x[0]+x[-1])/(1/len(x)+1) if x else 0
... 
>>> addFirstAndLast([])
0
>>> addFirstAndLast([1])
1
>>> addFirstAndLast([1,3])
4

注1:只有当list的长度为1时,(1/len(x)+1)的结果才是2,所以您将第一个和最后一个元素的和除以2,否则它除以1。在

注意2:如果您在python3中,使用//代替/。在

def addFirstAndLast(x):
    if x:
        return sum(zip(*filter(lambda (i,s): i == 0 or i == len(x) - 1, enumerate(x)))[1])
    else:
        return 0

枚举列表中的元素,过滤,解压缩,然后返回总和。在

Kasra的答案要好得多,但这是一个稍微不同的方法去做它。由于x[0]总是在存在时返回,所以您可以检查是否也应该添加x[-1]。在

def firstAndLast(x):
    if x:
        value = x[0]
        if len(x)>1:
            value += x[-1]
        return value
    return 0

相关问题 更多 >

    热门问题