python3學習之列表
- 2020 年 1 月 3 日
- 筆記
列表:
L.append(object) 追加
備註:append將obj作為一個整體追加,無論obj是字元串、數字、字典、列表等,當是字典時全部插入,跟L.extend(iterable) 不同
test = [1,2,3,4,5]
test1 = [6,7,8,9]
test.append(test1) : [1, 2, 3, 4, [6, 7, 8, 9]]
test.append(10) : [1, 2, 3, 4,10]
L.copy() 複製
備註:沒有參數,採用 test2 = test.copy()的方法獲取新的列表,該列表在記憶體中被新建,有新id
test2 = test.copy()
In [25]: id(test2 )
Out[25]: 140016313353992
In [26]: id(test)
Out[26]: 140016297719112
L.extend(iterable) 擴展(注意跟追加的區別)
備註:iterable 可以是列表、元組、字典。它將iterable中的元素追加到L中,當是字典時只追加item,沒有追加value
In [43]: test=[1,2,3]
In [45]: test.extend([4,5,6])
In [46]: print(test)
[1, 2, 3, 4, 5, 6]
In [47]: test.extend((7,8))
In [48]: print(test)
[1, 2, 3, 4, 5, 6, 7, 8]
In [49]: test.extend({9:'aaa',10:'bbb'})
In [50]: print(test)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
L.insert(index, object) 插入
備註:在index前插入,index從0開始,obj作為一個整體,無論是列表、元組、字典等,當是字典時全部插入,跟L.extend(iterable) 不同
In [53]: print(test)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [54]: test.insert(3,'aaaa')
In [55]: print(test)
[1, 2, 3, 'aaaa', 4, 5, 6, 7, 8, 9, 10]
In [56]: test.insert(3,[1,2,3])
In [57]: print(test)
[1, 2, 3, [1, 2, 3], 'aaaa', 4, 5, 6, 7, 8, 9, 10]
L.pop([index]) 彈出
L.remove(value) 移除
L.clear() 清空
備註:pop的參數是index,remove的參數是value,目的一樣,clear是刪除所有
L.sort(key=None,reverse=False) 排序
備註:默認是正序,即:1 2 3.... a b c...;reverse=True時是倒序,key參數一般不用,L中不可以包含嵌套列表、字典等
L.count(value) 計數
備註:返回值等於value出現的次數
L.index(value, [start, [stop]]) 查找
備註:返回值是在指定的範圍內第一次出現的等於value的index,stop=最大index+1才能判斷到最後一個value
In [117]: print(tt)
[5, 4, 3, 2, 1, [4, 5, 6, 9], 4]
In [119]: tt.index(4,2,7)
Out[119]: 6
In [118]: tt.index(4,2,6)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-118-900c1655e582> in <module>()
----> 1 tt.index(4,2,6)
ValueError: 4 is not in list
L.reverse() 倒序
備註:不是value排序,只是index倒個順序,對列表的數據結構沒要求,注意和sort的區別
列印1:簡單列表
tt = [1,2,3]
In [142]: for i in tt:
.....: print(i)
.....:
1
2
3
列印2:value是成對出現時
tt=[(2,3),(4,5),(6,7)]
In [147]: for a,b in tt:
.....: print(a,b)
.....:
2 3
4 5
6 7
