译(二十八)-Python如何按下标删除列表元素

文章首发及后续更新:https://mwhls.top/3067.html
新的更新内容请到mwhls.top查看。
无图/无目录/格式错误/更多相关请到上方的文章首发页面查看。

*热门问题目录

如有翻译问题欢迎评论指出,谢谢。

目录 1. Python如何按下标删除列表元素 2. How to remove an element from a list by index

Python如何按下标删除列表元素

  • Joan Venge asked:

    • 怎么按下标移除Python列表中的元素。
    • 我找到了list.remove函数,但如果我想删除最后一个元素,该怎么写?它好像默认搜索列表,但我不希望它在执行的时候进行搜索。
  • Answers:

    • unbeknown – vote: 2140

    • del可以删除指定下标的元素:

    • >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      >>> del a[-1]
      >>> a
      [0, 1, 2, 3, 4, 5, 6, 7, 8]

    • 且支持分片删除:

    • >>> del a[2:4]
      >>> a
      [0, 1, 4, 5, 6, 7, 8, 9]

    • 教程见

    • Jarret Hardie – vote: 763

    • 试试pop

    • a = [‘a’, ‘b’, ‘c’, ‘d’]
      a.pop(1)
      # now a is [‘a’, ‘c’, ‘d’]

    • 无参数的pop默认删除最后一个元素:

    • a = [‘a’, ‘b’, ‘c’, ‘d’]
      a.pop()
      # now a is [‘a’, ‘b’, ‘c’]


How to remove an element from a list by index

  • Joan Venge asked:

    • How do I remove an element from a list by index in Python?
      怎么按下标移除Python列表中的元素。
    • I found the list.remove method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don\’t want any search to be performed.
      我找到了list.remove函数,但如果我想删除最后一个元素,该怎么写?它好像默认搜索列表,但我不希望它在执行的时候进行搜索。
  • Answers:

    • unbeknown – vote: 2140

    • Use del and specify the index of the element you want to delete:
      del可以删除指定下标的元素:

    • >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      >>> del a[-1]
      >>> a
      [0, 1, 2, 3, 4, 5, 6, 7, 8]

    • Also supports slices:
      且支持分片删除:

    • >>> del a[2:4]
      >>> a
      [0, 1, 4, 5, 6, 7, 8, 9]

    • Here is the section from the tutorial.
      教程见

    • Jarret Hardie – vote: 763

    • You probably want pop:
      试试pop

    • a = [‘a’, ‘b’, ‘c’, ‘d’]
      a.pop(1)
      # now a is [‘a’, ‘c’, ‘d’]

    • By default, pop without any arguments removes the last item:
      无参数的pop默认删除最后一个元素:

    • a = [‘a’, ‘b’, ‘c’, ‘d’]
      a.pop()
      # now a is [‘a’, ‘b’, ‘c’]

上一篇:数据结构与算法分析-表,栈,队列


下一篇:Vue自定义事件