首页 > 解决方案 > 切片可迭代 - 函数不起作用(python)

问题描述

我被提出了以下问题:

创建一个名为 first_and_last_4 的新函数。它将接受一个可迭代的,但是这一次,它将前四个和最后四个项目作为单个值返回。

这是我的代码:

def first_and_last_4(x):
    first_4 = x[:4]
    last_4 = x[-4:]
    return (first_4.extend(last_4))

我也试图简化这一点:

def first_and_last_4(x):
    return x[:4] + x[-4:]

错误

笨蛋:找不到first_4

你能帮我吗?

标签: pythonpython-3.xlistslice

解决方案


试试这个:

def first_and_last_4(x):
    return x[:4]+x[-4:] #you had indentation problem here

推荐阅读