python - 切片可迭代 - 函数不起作用(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
你能帮我吗?
解决方案
试试这个:
def first_and_last_4(x):
return x[:4]+x[-4:] #you had indentation problem here
推荐阅读
- android - Android WorkManager:是否可以设置任务的最大执行持续时间
- reactjs - npx serve 提供主目录而不是 index.html
- python - 将数据堆叠到具有两个标题的行中,并且第一个标题不合并
- windows - Windows libvirt/QEMU 来宾虚拟机在重新启动后将时区重置为主机时区
- r - 在 R 中将字母映射到数字
- python - openCV库中的getPerspectiveTransform()函数是如何找到变换矩阵的?
- kubernetes - NodePort 与 kube-apiserver 的 hostPort 冲突
- c++ - 访问另一个类中的一个类成员
- css - 使用css隐藏div内的div元素
- javascript - 有没有办法创建一个对象的所有键都需要的类型?