❶ my_foods = [‘pizza’, ‘falafel’, ‘carrot cake’]
❷ friend_foods = my_foods[:]
print(“My favorite foods are:”)
print(my_foods)
print("\nMy friend’s favorite foods are:")
print(friend_foods)
结果:
My favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’]
My friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’]
my_foods = [‘pizza’, ‘falafel’, ‘carrot cake’]
❶ friend_foods = my_foods[:]
❷ my_foods.append(‘cannoli’)
❸ friend_foods.append(‘ice cream’)
print(“My favorite foods are:”)
print(my_foods)
print("\nMy friend’s favorite foods are:")
print(friend_foods)
结果:
My favorite foods are:
❹ [‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’]
My friend’s favorite foods are:
❺ [‘pizza’, ‘falafel’, ‘carrot cake’, ‘ice cream’]
切片复制,两个列表无关联
直接赋值,两个列表有关联
my_foods = [‘pizza’, ‘falafel’, ‘carrot cake’]
#列表会关联,尽量避免如此赋值
❶ friend_foods = my_foods
my_foods.append(‘cannoli’)
friend_foods.append(‘ice cream’)
print(“My favorite foods are:”)
print(my_foods)
print("\nMy friend’s favorite foods are:")
print(friend_foods)
本文通过实例详细解析了Python中列表的深拷贝与浅拷贝的区别,展示了如何通过切片操作实现列表的深拷贝,避免直接赋值导致的列表关联问题,确保两个列表独立变化。
1万+

被折叠的 条评论
为什么被折叠?



