1. 程式人生 > >python3 -- 列表操作 -深拷貝、淺拷貝、遍歷

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)