python學習Day2之數據結構
阿新 • • 發佈:2018-02-01
數據 一個 log ola ces pro 一維數組 位置 int
列表[list]:
列表是Python中最基本的數據結構,列表中每個元素都分配一個位置
列表也稱之為數組,數組可分為一維數組,多維數組
#一維數組 list = [‘Denny‘,‘Jenny‘,‘Liming‘,‘Lilei‘,‘Hanmeimei‘] #多維數組 #二維數組 list1=[1,2,3,4,[51,52,53,54],6,,78] #三維數組 list2=[1,2,3,4,[xiaoming[18,175],xiaola# 列list = [‘吉娃娃1‘,‘吉娃娃2‘,‘吉娃娃3‘,‘吉娃娃4‘]
a1 = list[0] a2 = list[1] a3 = list[2] a4= list[3] # 按下標取值標 print(‘第0個元素:‘,a1 ) print(‘第1個元素:‘,a2) print(‘第2個元素:‘,a3) print(‘第3個元素:‘,a4) 運行結果: D:\Python\Miniconda3\python.exe 第0個元素: 吉娃娃1 第1個元素: 吉娃娃2 第2個元素: 吉娃娃3 第3個元素: 吉娃娃4 Process finished with exit code 0
列表的基本操作:增、刪、改、查
增:
1 # 增 2 方式一: 3 list = [‘Denny‘,‘Jenny‘,‘Lilei‘,‘Hanmeimei‘]4 #append默認在最後的位置添加元素 5 list.append(‘Liming‘) 6 print(list) 7 8 運行結果: 9 D:\Python\Miniconda3\python.exe 10 [‘Denny‘, ‘Jenny‘, ‘Lilei‘, ‘Hanmeimei‘, ‘Liming‘] 11 Process finished with exit code 0 12 13 14 方式二: 15 list = [‘Denny‘,‘Jenny‘,‘Lilei‘,‘Hanmeimei‘] 16 #在指定位置中填寫下標 17 list.insert(2,‘Liming‘) 18 print(list) 19 20 運行結果: 21 D:\Python\Miniconda3\python.exe 22 [‘Denny‘, ‘Jenny‘, ‘Liming‘, ‘Lilei‘, ‘Hanmeimei‘] 23 Process finished with exit code 0
刪
# 刪 方式一: #刪除指定位置的元素 list = [‘Denny‘,‘Jenny‘,‘Liming‘,‘Lilei‘,‘Hanmeimei‘] del list[3] print(list) 運行結果: D:\Python\Miniconda3\python.exe [‘Denny‘, ‘Jenny‘, ‘Liming‘, ‘Hanmeimei‘] Process finished with exit code 0 方式二: list = [‘Denny‘,‘Jenny‘,‘Liming‘,‘Lilei‘,‘Hanmeimei‘] #pop不寫指定位置默認刪除最後的元素 list.pop() print(list) 運行結果: D:\Python\Miniconda3\python.exe [‘Denny‘, ‘Jenny‘, ‘Liming‘, ‘Lilei‘] Process finished with exit code 0 方式三: list = [‘Denny‘,‘Jenny‘,‘Liming‘,‘Lilei‘,‘Hanmeimei‘] #pop也可以刪除指定位置的元素 list.pop(1) print(list) 運行結果: D:\Python\Miniconda3\python.exe [‘Denny‘, ‘Liming‘, ‘Lilei‘, ‘Hanmeimei‘] Process finished with exit code 0 方式四: list = [‘Denny‘,‘Jenny‘,‘Liming‘,‘Lilei‘,‘Hanmeimei‘] #remove刪除指定元素 list.remove(‘Jenny‘) print(list) 運行結果: D:\Python\Miniconda3\python.exe [‘Denny‘, ‘Liming‘, ‘Lilei‘, ‘Hanmeimei‘] Process finished with exit code 0 方式五: list = [‘Denny‘,‘Jenny‘,‘Liming‘,‘Lilei‘,‘Hanmeimei‘] #清空列表 list.clear() print(list) 運行結果: D:\Python\Miniconda3\python.exe [] Process finished with exit code 0
改
#改 list = [‘Denny‘,‘Jenny‘,‘Liming‘,‘Lilei‘,‘Hanmeimei‘] list[1] = ‘xiaoming‘ print(list) 運行結果: D:\Python\Miniconda3\python.exe [‘Denny‘, ‘xiaoming‘, ‘Liming‘, ‘Lilei‘, ‘Hanmeimei‘] Process finished with exit code 0
查
list = [‘Denny‘,‘Jenny‘,‘Liming‘,‘Lilei‘,‘Hanmeimei‘] #根據下標進行查詢 a = list[1] #-1取最後一個元素 b = list[-1] print(a) print(b) 運行結果: D:\Python\Miniconda3\python.exe Jenny Hanmeimei Process finished with exit code 0
python學習Day2之數據結構