简体   繁体   English

在Python中,在不创建新列表的情况下按索引从列表中删除元素的最佳方法是什么?

[英]In Python, what is the best way to remove a elements from a list by index under the condition that the no new list is created?

I would like to remove all elements corresponding to an index from another list. 我想从另一个列表中删除与索引相对应的所有元素。 For example, 例如,

my_lst = [100,200,300,400,500,600,700,800,900,1000] my_lst = [100,200,300,400,500,600,700,800,900,1000]

I would like to remove the elements at indexes idxs = [1,3,9,6,4] . 我想删除索引为idxs = [1,3,9,6,4]的元素。

What is the preferred way to do this under the constraint that the list itself should be modified (ie Do not generate a new list -- so no list comprehensions)? 在应修改列表本身的约束下(例如,不生成新列表-因此无需列表理解),首选的方法是什么?

Essentially, what is the closest I can come to for 本质上,我能找到的最接近的是什么

del my_lst[idxs] del my_lst [idxs]

[100,300,600,700,800,900] [100,300,600,700,800,900]

The problem is that when an item is deleted, the index shifts from that point on. 问题在于,当删除项目时,索引从该点开始移动。 So solutions such as this will not work. 因此,如溶液将无法正常工作。 I have looked through other solutions too. 我也看过其他解决方案。

You can remove later indexes first so their position does not get shifted by removing smaller ones first: 您可以先删除以后的索引,这样它们的位置就不会因为先删除较小的索引而移位:

my_lst = [0,100,200,300,400,500,600,700,800,900,1000]  # added 0 index number


# sort reversed: 9,6,4,3,1 
for i in sorted([1,3,9,6,4], reverse=True):
    del my_lst[i]

print(my_lst)

Output: 输出:

[0, 200, 500, 700, 800, 1000]

my_lst = [100,200,300,400,500,600,700,800,900,1000] my_lst = [100,200,300,400,500,600,700,800,900,1000]

idxs = [1,3,9,6,4] idxs = [1,3,9,6,4]

for i in range(0,len(idxs)):
    my_lst[idxs[i]]='d'

my_lst = [x for x in my_lst if x != 'd']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM