python基礎-列表(7)

1、列表格式

列表名 = [列表元素1,列表元素2,列表元素3,… ]

說明:app

  1. 列表元素之間是有順序的,也是經過下標表示,第一個元素的小標爲0.
  2. 列表元素能夠不是同種類型,任何類型都行
  3. 列表一般當作容器,用來存放多個元素

 

2、列表的遍歷循環

for循環遍歷列表spa

nameList = ["張三","李四","王五","趙六"] for name in nameList: print(name)

運行結果以下:code

張三
李四
王五
趙六

while循環遍歷列表blog

nameList = ["張三","李四","王五","趙六"] i= 0 while i<len(nameList): print(nameList[i]) i+=1

運行結果以下:排序

張三
李四
王五
趙六

 

3、列表的相關操做

一、append:經過append能夠向列表添加元素rem

nameList = ["張三","李四","王五","趙六"] print(nameList) print("----------------分界線-----------------") nameList.append("侯七") print(nameList)

運行結果以下:字符串

['張三', '李四', '王五', '趙六'] ----------------分界線----------------- ['張三', '李四', '王五', '趙六', '侯七']

二、extend:能夠將另外一個集合中的元素逐一添加到列表中for循環

listA = [1,2] listB = [3,4] listA.extend(listB) print(listA)

運行結果爲:[1, 2, 3, 4]class

三、insert(index, object) 在指定位置index前插入元素object容器

numList = [1,2,3,4] numList.insert(0,"a") print(numList)

運行結果爲:['a', 1, 2, 3, 4]

四、經過下標修改元素

numList = [1,2,3,4] numList[1] = "A"
print(numList)

運行結果爲:[1, 'A', 3, 4]

五、查找元素

  • in(存在),若是存在那麼結果爲true,不然爲false
  • not in(不存在),若是不存在那麼結果爲true,不然false
numList = [1,2,3,4] if 2 in numList: print("2在numList裏面") else: print("2不在numList裏面")

運行結果爲:2在numList裏面

六、index和count:用法和字符串中差很少

strList = ['a','b','c','d','a','b','b'] ind = strList.index('b') con = strList.count('b') print(ind) print(con)

打印結果爲:0和3。index也是會找到第一個知足狀況的後面就不會再找了

七、刪除元素

  • del:根據下標進行刪除
  • pop:刪除最後一個元素
  • remove:根據元素的值進行刪除
nameList = ["張三","李四","王五","趙六","侯七"] del nameList[2] print(nameList)

運行結果爲:['張三', '李四', '趙六', '侯七']

nameList = ["張三","李四","王五","趙六","侯七"] nameList.pop() print(nameList)

運行結果爲:['張三', '李四', '王五', '趙六']

nameList = ["張三","李四","王五","趙六","侯七"] nameList.remove("李四") print(nameList)

運行結果爲:['張三', '王五', '趙六', '侯七']

八、排序(sort,reverse)

numList = [1,4,3,5,2] numList.reverse() print(numList)

運行結果爲:[2, 5, 3, 4, 1],倒序

numList = [1,4,3,5,2] numList.sort() print(numList)

運行結果爲:[1, 2, 3, 4, 5],升序

numList = [1,4,3,5,2] numList.sort(reverse = True) print(numList)

運行結果爲:[5, 4, 3, 2, 1],降序

相關文章
相關標籤/搜索