gpt4 book ai didi

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

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

我有一个如下所示的列表:

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']

最佳答案

我认为你需要:

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"))

关于python - 在列表中插入特定索引处的元素,覆盖相同索引处的元素或扩展列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58218180/

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