gpt4 book ai didi

python - 从 python 数组中删除给定元素索引作为列表的元素

转载 作者:行者123 更新时间:2023-12-01 09:09:21 24 4
gpt4 key购买 nike

我开始用 python 编程。我想根据我拥有的索引值列表从数组中删除元素。这是我的代码

x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]

del_list = [0, 4, 11]

desired output = [45, 55, 6, 37, 656, 78, 8, 99, 9]

这是我所做的

x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]

index_list = [0, 4, 11]

for element in index_list:
del x[element]

print(x)

我收到此错误。 我可以发现,由于删除元素,列表会缩短并且索引超出范围。但我不知道该怎么做

Traceback (most recent call last):
IndexError: list assignment index out of range

最佳答案

您还可以使用枚举:

x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]

index_list = [0, 4, 11]
new_x = []
for index, element in enumerate(x):
if index not in index_list:
new_x.append(element)
print(new_x)

关于python - 从 python 数组中删除给定元素索引作为列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51797321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com