1俗孝、列表的slice包含3個屬性俗冻,起始位置叹哭、結(jié)束位置和步長
image.png
>>> listone[0:6]
[0, 1, 2, 3, 4, 5]
>>> listone[0:6:2]
[0, 2, 4]
1.2.且步長不能為0乏矾,否則報錯
>>> listone[::0]
Traceback (most recent call last):
File "", line 1, in
listone[::0]
ValueError: slice step cannot be zero
>>>
1.3.步長可以為負數(shù),倒序排列
>>> listone[::-2]
[8, 6, 4, 2, 0]
>>>
2晴圾、習(xí)題
2.1.切片拷貝是否可以簡化為 listtwo = listone 懦冰?
>>> listtwo = listone[:] #切片拷貝至listtwo
>>> listtwo
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> listthree = listone #切片拷貝至listthree
>>> listthree
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> listone.append(9) #listone列表內(nèi)增加元素‘9’
>>> listone
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> listtwo #listtwo列表沒有任何變化灶轰,可以確定listtwo是一個獨立列表
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> listthree #listthree只是列表one的另外一個名稱,one改變其也隨之改變
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
3刷钢、列表中的操作符應(yīng)用
3.1.邏輯操作符
>>> l1 = [1, 2, 3]
>>> l2 = [2, 3, 4]
>>> l3 = [3, 4, 5]
>>> l1 < l2
True
----------------------------------------
>>> (l1 < l2) and (l2 < l3)
True
----------------------------------------
>>> l4 = l1 + l2
>>> l4
[1, 2, 3, 2, 3, 4]
注:‘+’相當(dāng)于extend() 笋颤,‘+’兩邊的對象類型必須一致
>>> l1 * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> l1 *= 3
>>> l1
[1, 2, 3, 1, 2, 3, 1, 2, 3]
----------------------------------------
>>> 1 in l1
True
>>> 4 in l1
False
>>> 4 not in l1
True
----------------------------------------
>>> l4 = [1, ['a', 'b'], 2]
>>> a in l4
False
>>> 'a' in l4
False
>>> a in l4[1]
False
>>> 'a' in l4[1]
True
4、列表的常用方法
4.1.count()内地,計算列表中參數(shù)出現(xiàn)的次數(shù)
>>> l1
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> l1.count(1)
3
4.2.index()伴澄,找到元素首次出現(xiàn)的位置索引號
>>> l1
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> l1.index(3)
2
>>> l1.index(3, 0, 7)
2
>>> l1.index(3, 3, 7)
5
注:index(元素,起始索引位置阱缓,結(jié)束索引位置)
4.3.reverse()非凌,將列表內(nèi)的元素倒序排列
>>> l4
[1, ['a', 'b'], 2]
>>> l4.reverse()
>>> l4
[2, ['a', 'b'], 1]
4.4.sort() 將列表內(nèi)的元素正序排列,sort()方法有3個參數(shù)sort(func),sort(key),sort(reverse= False/True)[reverse參數(shù)默認是False]
>>> l5
[1, 3, 5, 20, 50, 21, 60, 15, 26]
>>> l5.sort()
>>> l5
[1, 3, 5, 15, 20, 21, 26, 50, 60]
4.5.clear()荆针,清空列表中的所有元素敞嗡,列表還在颁糟,但列表內(nèi)的元素已經(jīng)全部清空
>>> l5.clear()
>>> l5
[]