python3 -- 列表操作 -深拷贝、浅拷贝、遍历

列表操作 -浅拷贝(copy),深拷贝

1.浅拷贝(copy),深拷贝

1.1 浅拷贝

# coding:utf-8
# python3 -- list列表操作(拷贝copy)

# 注意文件命名方式:不能 与关键字copy等发生冲突

# 浅拷贝,只拷贝第一层,2层以上 都是拷贝元素的地址
list_names = ["he", "li", ["liu", "li"], "fu", "chen"]
list_names2 = list_names.copy()
list_names[3] = "平"
print(list_names)
print(list_names2)

# 只是name,指向了list_names这个列表存储地址
name = list_names
print(name)
# 多维列表:,所以2层以后的元素,会跟着原来的列表改变
list_names[2][0] = "高"
print(list_names)
print(list_names2)

2.深拷贝

# coding:utf-8
# python3 -- list列表操作(深拷贝copy)

import copy

# 深拷贝:拷贝的内容 不会随原列表list_names内容的更改而更改
list_names = ["he", "li", ["liu", "li"], "fu", "chen"]
list_names2 = copy.deepcopy(list_names)
list_names[3] = "平"
print(list_names)
print(list_names2)

# 多维列表
list_names[2][0] = "高"
print(list_names)
print(list_names2)

3. 遍历 列表切片

# coding:utf-8
# python3 -- list列表操作 (遍历)
list_names = ["he", ["liu", "li"], "li",  "fu", "chen", "liu", "gao"]
# 步长切片
# range(1, 10, 2)
print(list_names[0:-1:2])
print(list_names[::2])
# 表示0 到 -1 ,从头到尾打印
print(list_names[:])

for i in list_names:
    print(i)

你可能感兴趣的:(python)