将特定索引处的元素插入列表,覆盖相同索引处的元素或扩展列表

时间:2019-10-03 11:26:25

标签: python python-3.x list

我有一个看起来像这样的列表:

a_list = ['A','B','C','D']

我想实现类似的功能(能够扩展列表):

new_index = 6
new_value = 'AA'
a_list = insert_value(new_index, new_value)
print(a_list)
#['A','B','C','D','','','AA']

还有类似的东西(可以覆盖new_value):

new_index = 2
new_value = 'AA'
a_list = insert_value(new_index, new_value)
print(a_list)
#['A','B','AA','D']

2 个答案:

答案 0 :(得分:2)

我认为您需要:

def expand_insert(lst, idx, ele):
    if len(lst) < idx:
        void = idx - len(lst)

        for i in range(void):
            lst.append("")
        lst.append(ele)
    else:
        lst[idx] = ele
    return lst

print(expand_insert(a_list, 6, "AA"))

答案 1 :(得分:0)

a_list = ['A','B','C','D']
index = [6,2]

for i in index:
if i >= len(a_list):
    a_list.extend([''] * (i - len(a_list) + 1))
    print(a_list)
    a_list[i] = 'BBB'
else:
    a_list[i] = 'AAA'

a_list
['A', 'B', 'AAA', 'D', '', '', 'BBB']