如何在Python中的函数中更改list2而不更改list1?

fykwrbwg  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(114)

此问题已在此处有答案

How do I clone a list so that it doesn't change unexpectedly after assignment?(24回答)
关闭22小时前.

def change_list(ls):
    ls1 = ls
    ls1[1] = "?"
    return ls1

list1 = ['a', 'b', 'c', 'd']
list2 = change_list(list1)

print(list1)
print(list2)

结果:

List 1 - ['a', '?', 'c', 'd']
List 2 - ['a', '?', 'c', 'd']

预期结果:

List 1 - ['a', 'b', 'c', 'd']
List 2 - ['a', '?', 'c', 'd']
ac1kyiln

ac1kyiln1#

您需要创建一个新列表,而不是修改原始列表:

def change_list(ls):
    ls1 = ls.copy()
    ls1[1] = "?"
    return ls1

另一种选择是用原始列表的切片构建新列表:

def change_list(ls):
    return ls[:1] + ["?"] + ls[2:]

相关问题