python 列表操作

2022-06-27 04:33:11 字數 1575 閱讀 3843

count 方法

a = ['fdrdr','peng','chenxi','yugfd','wsd','peng']   #定義的列表

b = a.count('peng') #查出peng這個元素,在列表裡有幾個

print(b,a)

測試

d:\pyth\python.exe d:/python/map.py

2 ['fdrdr', 'peng', 'chenxi', 'yugfd', 'wsd', 'peng']

extend 方法

a = ['fdrdr','peng','chenxi','yugfd','wsd','peng']   #定義的列表

b = ['wsx','wer']

a.extend(b) #將b元素追加到a元素裡

print(a,b)

結果

d:\pyth\python.exe d:/python/map.py

['fdrdr', 'peng', 'chenxi', 'yugfd', 'wsd', 'peng', 'wsx', 'wer'] ['wsx', 'wer']

process finished with exit code 0

index方法

a = ['fdrdr','peng','chenxi','yugfd','wsd','peng']   #定義的列表

b = a.index('chenxi') #獲取chenxi在列表裡的下標,並賦值給b

print(a[b:b+2])

結果

['chenxi', 'yugfd']

reverse方法

a = ['fdrdr','peng','chenxi','yugfd','wsd','peng']

print(a)

a.reverse() 將列表元素整體翻過來

print(a)

結果

['fdrdr', 'peng', 'chenxi', 'yugfd', 'wsd', 'peng']

['peng', 'wsd', 'yugfd', 'chenxi', 'peng', 'fdrdr']

元組與列表巢狀(元組不能修改,元組的定義方式())

a = [[1,2,3],'xi',4,(1,2,3)]

b=a.index((1,2,3)) #取出元組在列表裡的下標

print(a[b][2]) #查列表元組裡3

結果

3

修改列表巢狀列表的值

a = [[1,2,3],'xi',4,(1,2,3)]

print(a[0][0]) #修改前列印

a[0][2]=4 #修改列表的值

print(a[0][2]) #修改後列印

結果

1

4

python列表建立操作 python列表操作

建立列表 sample list a 1,a b python 列表操作 sample list a b 0,1,3 得到列表中的某乙個值 value start sample list 0 end value sample list 1 刪除列表的第乙個值 del sample list 0 在列...

python列表建立操作 python列表操作

列表是最常用的python資料型別,它可以作為乙個方括號內的逗號分隔值出現。列表的資料項不需要具有相同的型別。如 list a b 2,5,1 1 新建列表 stus 建立空列表 stus1 list 建立空列表 print stus print stus1 stus 范冰冰 維達 soon 上述 ...

python 列表操作

list 一種順序儲存結構,序列的一種,列表元素可以是任何型別,類似陣列,引用型別。格式定義 olist 1,str 定義乙個空的list olist 獲取列表元素個數 len olist 刪除乙個列表 del olist 刪除乙個列表元素 del list i 支援 olist1 olist2 列...