Python - Python3 列表
1、代碼及其說明如下
if __name__ == '__main__':
list1 = ['Google', 'Baidu', 1997, 2000]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]
# 通過索引訪問
print(list1[0])
# 截取訪問,包含頭,不包含尾
print(list1[1:3])
# 修改值
list1[2] = 1995
print(list1[2])
# 刪除值
del list2[3]
print(list2)
# 獲取長度
print(len(list1))
# 拼接
print(list1 + list3)
# 給定重複值
print(['Good'] * 10)
# 判斷是否存在
print('Google' in list1)
# 通過下標正向讀取
print(list1[1])
# 通過下標反向讀取,從-1開始
print(list1[-2])
# 輸出某一段
print(list1[1:])
# 創建多維列表
print([list1, list2, list3])
# 獲取最大值
print(max(list2))
# 獲取最小值
print(min(list2))
# 轉成列表
print(list(list1))
# 追加對象
list1.append('Ali')
print(list1)
# 統計某個對象有多少個
list2.append(3)
list2.append(3)
print(list2.count(3))
# 在列表尾部追加新的列表
list1.extend(list3)
print(list1)
# 找出某個值在列表裏面的索引位置,只匹配第一個符合條件的
print(list2.index(3))
# 插入數據,如果插在中間,會導致後面的數據下標後移
list1.insert(3, 1996)
print(list1)
# 移除列表中的一個元素(默認最後一個元素),並且返回該元素的值
list2.pop()
print(list2)
# 移除列表中某個值的第一個匹配項
list2.remove(3)
print(list2)
# 列表取反
list2.reverse()
print(list2)
# 排序,默認正序
list2.sort()
print(list2)
# 複製列表
list4 = list2.copy()
print(list4)
# 清空列表
list2.clear()
print(list2)
輸出如下
E:\python_project_path\api_test\venv\Scripts\python.exe "E:\PyCharm\PyCharm 2020.1.2\plugins\python\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 64775 --file E:/python_project_path/api_test/study/for_list.py
pydev debugger: process 8376 is connecting
Connected to pydev debugger (build 201.7846.77)
Google
['Baidu', 1997]
1995
[1, 2, 3, 5]
4
['Google', 'Baidu', 1995, 2000, 'a', 'b', 'c', 'd']
['Good', 'Good', 'Good', 'Good', 'Good', 'Good', 'Good', 'Good', 'Good', 'Good']
True
Baidu
1995
['Baidu', 1995, 2000]
[['Google', 'Baidu', 1995, 2000], [1, 2, 3, 5], ['a', 'b', 'c', 'd']]
5
1
['Google', 'Baidu', 1995, 2000]
['Google', 'Baidu', 1995, 2000, 'Ali']
3
['Google', 'Baidu', 1995, 2000, 'Ali', 'a', 'b', 'c', 'd']
2
['Google', 'Baidu', 1995, 1996, 2000, 'Ali', 'a', 'b', 'c', 'd']
[1, 2, 3, 5, 3]
[1, 2, 5, 3]
[3, 5, 2, 1]
[1, 2, 3, 5]
[1, 2, 3, 5]
[]
Process finished with exit code 0