我有一个看起来像这样的列表:
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']
答案 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']