二、串列
Python串列可以同時包含資料、字串、物件、串列等資料型別
List1 = [1, 2, 'abc', 'def']
List2 = [5, 6, [1, 2, 'abc']]
1.串列添加
(1) append()
append()方法可用于在串列的最后追加一個元素
append(<插入的元素>)
List1.append('newItem') #append方法只能有一個引數
print(List1)
輸出結果:[1, 2, 'abc', 'def', 'newItem']
(2) extend()
extend()方法用于在串列的最后擴展另一個串列
extend(<拓展的串列>)
List1.extend([3, 4]) #extend方法同樣只能有一個引數
print(List1)
輸出結果:[1, 2, 'abc', 'def', 'newItem', 3, 4]
(3) insert()
insert()方法可在串列任意位置插入元素
insert(<插入位置>, <插入的元素>)
List1.insert(1, 'insertItem')
print(List1)
輸出結果:[1, 'insertItem', 2, 'abc', 'def', 'newItem', 3, 4]
2.串列洗掉
(1) remove()
remove()方法可以移除串列中的一個已知元素
remove(<洗掉的元素>)
List1 = [1, 'insertItem', 2, 'abc', 'def', 'newItem', 3, 4]
List1.remove('newItem') #不需要知道元素的位置
print(List1)
輸出結果:[1, 'insertItem', 2, 'abc', 'def', 3, 4]
(2) del
del陳述句可以按下標洗掉元素
del 串列名[<下標>]
del List1[2] # del是Python的陳述句,不是方法
print(List1)
輸出結果:[1, 'insertItem', 'abc', 'def', 3, 4]
(3) pop()
? pop()方法可以洗掉并回傳指定位置的元素
pop(<要洗掉元素的位置>) #如果沒有引數則默認洗掉最后一個元素
item = List1.pop()
print(List1)
print(item)
輸出結果:[1, 'insertItem', 'abc', 'def', 3]
4
3.串列分片
串列名[<分片開始位置>: <分片結束位置>: <步長>]
'''
若不寫開始位置則默認從第一個位置開始
若不寫結束位置則默認從最后個位置結束
若不寫步長則默認步長為1
'''
List1 = [1, 'insertItem', 'abc', 'def', 3]
print(List1[1:4]) #分片不改變原串列內容
print(List[2:])
print(List[:4:2])
輸出結果:['insertItem', 'abc', 'def']
['abc', 'def', 3]
[1, 'abc']
分片還支持負數索引以及負步數

步長可以是負數,改變方向(從尾部開始向左走):
print(List1[::-2])
輸出結果:[3, 'abc', 1]
串列復制應使用分片
List1 = [1, 'insertItem', 'abc', 'def', 3]
copy1 = List1[:] #將List1的內容復制到copy1中
copy2 = List1 #若直接賦值,copy2和List1指向同一內容,若對List1進行操作,copy2也被改變
4.串列常用運算子
(1) 比較運算子
list1 = [123, 456]
list2 = [234, 123]
list1 > list2 #把串列的第0個位置進行比較
輸出結果:false
(2) 串列拼接
list3 = list1 + list2 #用加號進行拼接
print(list3)
輸出結果:[123, 456, 234, 123]
? 不可以使用加號添加單個元素
? list3 + ‘newItem’
(3) 串列重復
print(list1 *= 3)
輸出結果:[123, 456, 123, 456, 123, 456]
(4) 成員關系運算子
123 in list1
輸出結果:true
234 not in list2
輸出結果:false
list4 = [123, ['abc', 'def'], 456]
'abc' in list4
輸出結果:false #成員關系運算子默認判斷最外層串列
'abc' in list4[1]
輸出結果:true
5.串列常用方法
(1) count()
? count()方法的作用是判斷某一元素在串列中的出現次數
count(<要判斷的元素>)
list5 = [1, 1, 1, 2, 3]
list5.count(1)
輸出結果:3
(2) index()
? index()方法用于查詢某一元素在串列中的位置
index(<要查詢的元素>, <查詢范圍起始位置>, <查詢范圍的結束位置>) #后兩個引數不寫則默認范圍為整個串列
list5.index(2)
輸出結果:3
(3) reverse()
? reverse()方法的作用是將串列前后翻轉
list5.reverse()
print(list5)
輸出結果:[3, 2, 1, 1, 1]
(4) sort()
? sort()方法則作用是用指定方法對串列進行排序
sort(<func>, <key>, <reverse=True/False>) #reverse默認為true
list6 = [8, 3 ,5 ,2 ,5, 0, 1]
print(list6.sort()) #默認為從小到大排序
輸出結果:[0, 1, 2, 3, 5, 5, 8]
print(list6.sort(reverse = True))
輸出結果:[8, 5, 5, 3, 2, 1, 0]
?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/183602.html
標籤:Python
下一篇:Matplotlib使用筆記
