#!/usr/bin/env python
# encoding: utf-8
'''
@author: JHC
@license: None
@contact: JHC000abc@gmail.com
@file: execfile_test.py
@time: 2022/3/29 17:13
@desc:解决删除列表中的元素,列表长度变化带来的删除不准确(数组下标越界)问题
'''
import copy

'''
1.
删除时候,被删除的列表长度会发生变化,将待删除的索引先按从小到大排序,变化后的列表要删除的元素的索引等于待删除索引列表中的元素值减去待删除列表中该值所对应的索引
删第几个向前移动几个
'''
list_given = [1, 5, 3, 10, 5, 4, 7, 8, 9]
index_to_delete = [-1, 0, 5]
index_to_delete.sort()
for counter, index in enumerate(index_to_delete):
    print(counter,index)
    print('*'*101)
    index = index - counter
    # print(counter, index)
    list_given.pop(index)
print(list_given)

'''
2.
    利用dict做中间变化
    (待删除的索引值不能为负数)
'''
list_given = [1, 5, 3, 10, 5, 4, 7, 8, 9]
index_to_delete = [1, 0, 5]
my_dict= {}
for index,var in enumerate(list_given):
    my_dict[index] = var
print(my_dict)
for i in index_to_delete:
    print(i)
    my_dict.pop(i)
result = list(my_dict.values())
print(result)

'''
3.
    深拷贝
    循环遍历取真实索引的是深拷贝的值,避免删除时列表长度变化对索引值准确度的影响
'''
list_given = [1, 5, 3, 10, 5, 4, 7, 8, 9]
list_given2 = copy.deepcopy(list_given)
for index,var in enumerate(list_given2):
    if index % 2 == 0:
        print(index)
        list_given.remove(list_given2[index])
        print(list_given)
    else:
        pass

print('list_given',list_given)



Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐