从列表中删除元素的最佳方法

编程入门 行业动态 更新时间:2024-10-23 11:31:37
本文介绍了从列表中删除元素的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道从列表中删除元素的最佳方法/有效方法是什么.

Python提供了少量函数:

  • some_list.remove(value),但是如果找不到值,则会引发错误.
  • some_list.pop(some_list[index]),删除列表中给定位置的项目,然后将其返回.
  • del (some_list[index]),它从给定索引中删除元素,它与pop有所不同,因为它不返回值.
  • 场景:

    • 如果您要删除的项目很少,则说一个元素或1到5之间.
    • 如果您必须依次删除多个项目.
    • 如果您必须根据条件删除其他项目.
    • 如果您有一个列表列表并想按顺序删除元素,该怎么办.

    解决方案

    使用列表理解:

    方案1:

    [item for item in my_list if 1 <= item <=5 ]

    方案2:

    to_be_removed = {'a', '1', 2} [item for item in my_list if item not in to_be_removed ]

    方案3:

    [item for item in my_list if some_condition()]

    场景4(嵌套列表理解):

    [[item for item in seq if some_condition] for seq in my_list]

    请注意,如果只想删除一项,则list.remove,list.pop和del肯定会非常快,但是在遍历列表时使用这些方法可能会导致意外输出./p>

    相关:循环忘记"以删除一些项

    I would like to know what is the best way/efficient way to remove element(s) from the list.

    There are few functions provided by Python:

  • some_list.remove(value), but it throws error if value is not found.
  • some_list.pop(some_list[index]), removes the item at the given position in the list, and return it.
  • del (some_list[index]), it removes element from the given index, it's different from pop as it doesn't return value.
  • Scenarios:

    • If you have few items to remove say one element or between 1 to 5.
    • If you have to remove multiple items in a sequence.
    • If you have to remove different items based on a condition.
    • How about if you have a list of lists and want to remove elements in sequence.

    解决方案

    Use a list comprehension:

    Scenario 1:

    [item for item in my_list if 1 <= item <=5 ]

    Scenario 2:

    to_be_removed = {'a', '1', 2} [item for item in my_list if item not in to_be_removed ]

    Scenario 3:

    [item for item in my_list if some_condition()]

    Scenario 4(Nested list comprehension):

    [[item for item in seq if some_condition] for seq in my_list]

    Note that if you want to remove just one item then list.remove, list.pop and del are definitely going to be very fast, but using these methods while iterating over the the list can result in unexpected output.

    Related: Loop "Forgets" to Remove Some Items

    更多推荐

    从列表中删除元素的最佳方法

    本文发布于:2023-11-01 18:27:07,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1550076.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:元素   方法   列表中

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!