001 Python list 索引
阿新 • • 發佈:2017-07-14
[] type 元組 com 不同 div aid mage image
# Python 3 基礎語法
● list 索引
○ -1代表最後一個
○ list可以放置各種各樣的類型
# -*- coding: UTF-8 -*- names = [‘Mark‘, ‘coloe‘,1,2,3,4,5,3.14,True] print(type(names)) print(names) print(names[1]) print(names[0]) print(names[-1])
● list 嵌套使用
1 # -*- coding: UTF-8 -*- 2 names = [‘Mark‘, ‘coloe‘, [‘I‘, ‘Love‘, ‘PoEdu‘,‘!‘,],1,2,3,4,5,3.14,True, [‘I‘, ‘Love‘, ‘Mark‘,‘!‘,]] 3 print(type(names)) 4 print(names) 5 print(names[2]) #嵌套的list 6 print(names[-1]) #嵌套的list 7 print(names[-1][1], names[2][2]) #獲取嵌套list 的值 並輸出
● list append[]
末尾加入
1 # -*- coding: UTF-8 -*- 2 names = [‘Mark‘, ‘coloe‘, [‘I‘, ‘Love‘, ‘PoEdu‘,‘!‘,]] 3 print(names) 4 names.append(‘Google‘) 5 print(names) 6 names.append(‘Baidu‘) 7 print(names) 8 names.append(‘PoEdu‘) 9 print(names)
● list insert[]
指定位置插入
參數1:位置
參數2:插入的值
1 # -*- coding: UTF-8 -*- 2 names = [‘Mark‘, ‘coloe‘, [ ‘Love‘, ‘PoEdu‘,‘!‘,]] 3 print(names) 4 names.insert(1,‘胡蘿蔔‘) 5 print(names) 6 names.insert(4,‘So Much !‘) 7 print(names)
● list clear()
清空索引
1 # -*- coding: UTF-8 -*- 2 names = [‘Mark‘, ‘coloe‘, [ ‘Love‘, ‘PoEdu‘,‘!‘,]] 3 names.insert(1,‘胡蘿蔔‘) 4 names.insert(4,‘So Much !‘) 5 names.clear() 6 print(names)
● list copy()
復制索引
1 # -*- coding: UTF-8 -*- 2 names = [‘Mark‘, ‘coloe‘, [ ‘Love‘, ‘PoEdu‘,‘!‘,]] 3 other = names.copy() 4 print(names) 5 print(other)
● list pop()
刪除索引末尾
參數1:刪除指定位置的數據
感覺跟出棧一樣
1 # -*- coding: UTF-8 -*- 2 names = [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘, ‘I‘, ‘J‘, ‘K‘,] 3 print(names) 4 names.pop() 5 print(names) 6 names.pop(0) 7 print(names) 8 names.pop(3) 9 print(names)
● Python 元組
Python的元組與列表類似,不同之處在於元組的元素不能修改。
元組使用小括號,列表使用方括號。
元組創建很簡單,只需要在括號中添加元素,並使用逗號隔開即可。
1 # -*- coding: UTF-8 -*- 2 names = (‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘, ‘I‘, ‘J‘, ‘K‘) 3 print(type(names)) 4 print(names) 5 #元祖訪問 6 print(names[0]) 7 print(names[1:5]) 8 print(names[6:]) 9 print(names[6:-1])
001 Python list 索引