从左侧删除列表元素

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,我们可以使用切片表示法从列表中删除元素。在这个挑战中,你需要编写一个函数,从列表的左侧删除指定数量的元素。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/default_arguments("Default Arguments") subgraph Lab Skills python/comments -.-> lab-13625{{"从左侧删除列表元素"}} python/lists -.-> lab-13625{{"从左侧删除列表元素"}} python/tuples -.-> lab-13625{{"从左侧删除列表元素"}} python/function_definition -.-> lab-13625{{"从左侧删除列表元素"}} python/default_arguments -.-> lab-13625{{"从左侧删除列表元素"}} end

从左侧删除列表元素

编写一个函数 drop(a, n=1),它接受一个列表 a 和一个可选整数 n 作为参数,并返回一个新列表,该列表从原始列表的左侧删除了 n 个元素。如果未提供 n,则该函数应仅删除列表的第一个元素。

def drop(a, n = 1):
  return a[n:]
drop([1, 2, 3]) ## [2, 3]
drop([1, 2, 3], 2) ## [3]
drop([1, 2, 3], 42) ## []

总结

在这个挑战中,你学习了如何使用切片表示法在 Python 中从列表中删除元素。你还编写了一个函数,用于从列表的左侧删除指定数量的元素。