此问题已在此处有答案:
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']
1条答案
按热度按时间ac1kyiln1#
您需要创建一个新列表,而不是修改原始列表:
另一种选择是用原始列表的切片构建新列表: