首页 > 解决方案 > 列表插入和变异

问题描述

def new_insert(lst, i, e):
    lst = lst[:i] + [e] + lst[i:]
    
a = [0, 1, 2, 3, 4, 6, 7]
new_insert(a, 5, 5)
#Expected output: a = [0, 1, 2, 3, 4, 5, 6, 7]
    
b = ['0', '1', '0']
new_insert(b, 0, '1')
#Expected output: b = ['1', '0', '1', '0']

    
new_insert([1,2,3], 1, 0)
#Expected output = None

对于上面的代码,将e添加到列表中时,我无法得到新修改列表的答案。当 e = 0 时,输出应返回 None。如何更改代码,以便获得预期的输出?

标签: pythonlist

解决方案


选项 1

您需要从以下位置返回修改后的列表new_insert

def new_insert(lst, i, e):
    return lst[:i] + [e] + lst[i:]

然后做:

a = [0, 1, 2, 3, 4, 6, 7]
a = new_insert(a, 5, 5)

选项 2

或者只是这样做:

def new_insert(lst, i, e):
    lst[:] = list[:i] + [e] + lst[i:]

如果您不想从函数中返回它。


推荐阅读