从列表中删除元素的最佳方法 [英] Best way to remove elements from a list

查看:89
本文介绍了从列表中删除元素的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Python提供了少量函数:

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

场景:

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

解决方案

使用循环忘记"以删除一些项

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:

  1. some_list.remove(value), but it throws error if value is not found.
  2. some_list.pop(some_list[index]), removes the item at the given position in the list, and return it.
  3. 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

这篇关于从列表中删除元素的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆