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

stackoverflow热门问题目录

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

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']

You may also like...

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注