Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从列表的不同索引中删除多个元素_Python - Fatal编程技术网

Python 从列表的不同索引中删除多个元素

Python 从列表的不同索引中删除多个元素,python,Python,我有一张这样的清单: >>> a = ['1G', '1G', '1G', '1G', '10G', '10G', '10G', '10G', '25G', '25G', '25G', '25G'] 以下是我想在列表a中更改的元素索引: >>> ind = [4, 8] >>> a ['1G', '1G', '1G', '1G', '40G', '10G', '10G', '10G', '100G', '25G', '25G', '25G

我有一张这样的清单:

>>> a = ['1G', '1G', '1G', '1G', '10G', '10G', '10G', '10G', '25G', '25G', '25G', '25G']
以下是我想在列表
a
中更改的元素索引:

>>> ind = [4, 8]
>>> a
['1G', '1G', '1G', '1G', '40G', '10G', '10G', '10G', '100G', '25G', '25G', '25G']
我想用以下内容更改第4和第8个索引元素:

>>> mode = ['40G', '100G']
我试过这个:

>>> for i, m in zip(ind, mode):
...  a[i] = m
这样,我就可以更新列表
a
中的第4和第8个索引元素:

>>> ind = [4, 8]
>>> a
['1G', '1G', '1G', '1G', '40G', '10G', '10G', '10G', '100G', '25G', '25G', '25G']
我想从
a
中删除第4个索引后的3个元素(即5、6、7)和第8个索引后的3个元素(即9、10、11),我无法一次性删除它们。有人能帮我解决这个问题吗

>>> for i, m in zip(ind, mode):
...  del a[i+1:i+4]
...

但在此之后,I loose index

问题在于,一旦删除了一个项目,元素的索引就会改变。但这个问题可以回避。一旦有了列表
a
,将要删除的索引存储在列表中并按相反顺序排序

a = ['1G', '1G', '1G', '1G', '40G', '10G', '10G', '10G', '100G', '25G', '25G', '25G']
del_ind = [5,6,7,9,10,11]
del_ind.sort()
del_ind = del_ind[::-1]
排序完成后,您可以继续删除项目。这样做的原因是,删除最后一项时,所有其他项的索引保持不变。所以现在你不必担心指数的变化-

for i in del_ind:
    del a[i]
print(a)
# ['1G', '1G', '1G', '1G', '40G', '100G']

作为Ev。Kounis提到,当您删除元素时,索引会向左移动一个位置,因此您必须对此进行说明。先这样做

idx_to_delete = [5, 6, 7, 9, 10, 11]
for i, x in enumerate(idx_to_delete):
    idx_to_delete[i] -= i

print(idx_to_delete)
[5, 5, 5, 6, 6, 6]
现在,您可以继续删除

a = ['1G', '1G', '1G', '1G', '40G', '10G', '10G', '10G', '100G', '25G', '25G', '25G']
for i in idx_to_delete:
    del a[i]

print(a) 
['1G', '1G', '1G', '1G', '40G', '100G']

我建议您使用
切片
功能:

a = [  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
index = [4, 8]

a = a[:index[0]] + a[index[0]+3:index[1]] + a[index[1]+3 :]

print(a)

# result: [1, 2, 3, 4, 8, 12, 13, 14, 15]

这是因为
切片
不会更改列表,而是返回所选切片的新副本。有关切片的更多信息,请查看

以下是我在评论中提到的两种解决方案:

赔偿:


从后面访问列表:


问题是删除一个元素后,索引会发生变化。所以你要么从头到尾地删除,要么在删除时对更改进行补偿。你是如何尝试删除这些列表项的,发生了什么?非常感谢@Ev。库尼斯!我喜欢第一种解决方案,清脆清晰。