Python3列表

2025-12-29 19:32:31

1 通过列表切片方式复制列表:

1.1 列表复制

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']

1.2 验证确实实现了两个列表

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']

可以看出通过切片方式复制列表,结果是生成了两个列表。

2 通过简单赋值方式复制列表:

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', 'ice cream']

My friend's favorite foods are:

['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']

可以看出两个列表是相同的,这并非我们想要的结果。

nicergj nicergj

nic***j@163.com

7年前 (2018-10-21)