译(二十八)-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']

版权声明:
作者:MWHLS
链接:https://mwhls.top/3067.html
来源:无镣之涯
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>