本文介绍了从列表中删除元素的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
some_list.remove(value),但是如果找不到值,则会引发错误.
some_list.pop(some_list[index]),删除列表中给定位置的项目,然后将其返回.
del (some_list[index]),它从给定索引中删除元素,它与pop有所不同,因为它不返回值.
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.
我想知道从列表中删除元素的最佳方法/有效方法是什么.
Python提供了少量函数:
场景:
- 如果您要删除的项目很少,则说一个元素或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:
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
更多推荐
从列表中删除元素的最佳方法
发布评论