1. 程式人生 > >python列表操作

python列表操作

int 不包含 move 結束 列表 通過 指定 count not

列表:
a = [1,2,3,‘wangwu‘,‘zhaoliu‘]
列表用中括號定義。可以保存多種類型的數據。
列表也是依靠下標獲取數據。
列表循環:使用for循環
nameList = [‘xiaowang‘,‘xiaozhang‘]
for name in nameList:
  print(name)
列表循環:使用while循環
i = 0
length = len(nameList)
while i<length:
  pirnt(nameList[i])
  i+=1
列表的增刪改查:
增:append
nameList.append(‘xiaoma‘)
增:insert
nameList.insert(1,‘laoli‘)
insert(index,obj)在指定位置index前插入元素obj.
增:extend
a = [1,2]
b = [3,4]
a.extend(b)
通過extend可以將另一個集合中的元素逐一添加到列表中
修改:通過下標重新賦值即可。
查找:in
if name in nameList:
  print(‘存在‘)
else:
  print(‘不存在‘)
如果存在結果為true,不存在結果為false
查找:not in
如果不存在結果為true,否則為false
查找:index
nameList.index(name,start,end)
查找nameList中是否包含name,包含則返回所在列表的下標。不包含則拋出異常。start表示開始下標(包含),end表示結束下標(不包含)。
查找:count
nameList.count(name)
查找nameList列表中包含name的個數。
刪除:del
del nameList[i]
根據下標進行刪除
刪除:pop
nameList.pop()
刪除最後一個元素
刪除:remove
nameList.remove(name)
根據元素的值進行刪除
列表的嵌套:
列表中包含列表,就是嵌套。

python列表操作