Python List 拼接时未就地修改?

问题描述 投票:0回答:1

我有一个字符列表。我想在给定索引处的字符之间插入一个字符串。 为此,我编写了一个函数来将项目(字符串)就地插入列表中。函数内的列表是正确的,但它没有修改我传递的原始列表。我相信 Python List 是可变的。

def insert_inplace(lst, idx, item_to_insert):
    lst = lst[:idx] + lst[idx+1:]
            
    lst[:idx] = lst[:idx]
    lst[idx+1:] = lst[idx:]
    lst[idx] = item_to_insert
    print(lst) 
    # getting correct answer here

string_list = ["a", "b", "c", "d", "e"]
replacement = "new inserted item"
i = 2
insert_inplace(string_list, i, replacement)
# string_list is not getting modified
python list mutable
1个回答
0
投票

您正在函数内重新分配 lst 变量。将 lst 重新分配给新列表会破坏原始列表之间的连接

def insert_inplace(lst, idx, item_to_insert):
    lst[idx:idx] = [item_to_insert]  # Insert item_to_insert at index idx
    print(lst)  # Print the modified list inside the function

string_list = ["a", "b", "c", "d", "e"]
replacement = "new inserted item"
i = 2
insert_inplace(string_list, i, replacement)
# string_list should now be modified
print(string_list)

输出

['a', 'b', 'new inserted item', 'c', 'd', 'e']

更简单的方法

def insert_inplace(lst, idx, item_to_insert):
    lst.insert(idx, item_to_insert)

string_list = ["a", "b", "c", "d", "e"]
replacement = "new inserted item"
i = 2
insert_inplace(string_list, i, replacement)
print(string_list)

产量相同

['a', 'b', 'new inserted item', 'c', 'd', 'e']

时间复杂度为o(n)

© www.soinside.com 2019 - 2024. All rights reserved.