如何按索引从列表中删除元素?
我找到了list.remove(),但这会缓慢地按值扫描列表中的项。
如何按索引从列表中删除元素?
我找到了list.remove(),但这会缓慢地按值扫描列表中的项。
当前回答
或者如果应删除多个索引:
print([v for i,v in enumerate(your_list) if i not in list_of_unwanted_indexes])
当然,也可以这样做:
print([v for i,v in enumerate(your_list) if i != unwanted_index])
其他回答
如前所述,最佳实践是del();或pop(),如果需要知道值。
另一种解决方案是仅重新堆叠所需的元素:
a = ['a', 'b', 'c', 'd']
def remove_element(list_,index_):
clipboard = []
for i in range(len(list_)):
if i is not index_:
clipboard.append(list_[i])
return clipboard
print(remove_element(a,2))
>> ['a', 'b', 'd']
eta:hmm……不会处理负指数值,会思考并更新
我想是吧
if index_<0:index_=len(list_)+index_
会修补它…但突然间这个想法似乎很脆弱。有趣的思想实验。似乎应该有一种“正确”的方法来实现append()/list理解。
思考
使用以下代码从列表中删除元素:
list = [1, 2, 3, 4]
list.remove(1)
print(list)
output = [2, 3, 4]
如果要从列表中删除索引元素数据,请使用:
list = [1, 2, 3, 4]
list.remove(list[2])
print(list)
output : [1, 2, 4]
或者如果应删除多个索引:
print([v for i,v in enumerate(your_list) if i not in list_of_unwanted_indexes])
当然,也可以这样做:
print([v for i,v in enumerate(your_list) if i != unwanted_index])
通常,我使用以下方法:
>>> myList = [10,20,30,40,50]
>>> rmovIndxNo = 3
>>> del myList[rmovIndxNo]
>>> myList
[10, 20, 30, 50]
这取决于你想做什么。
如果要返回删除的元素,请使用pop():
>>> l = [1, 2, 3, 4, 5]
>>> l.pop(2)
3
>>> l
[1, 2, 4, 5]
但是,如果您只想删除一个元素,请使用del:
>>> l = [1, 2, 3, 4, 5]
>>> del l[2]
>>> l
[1, 2, 4, 5]
此外,del允许您使用切片(例如del[2:])。