Python中append、extend與insert幾個方法的區別 ...
Python語言,看到向列表增加更多數據時被append(),extend(),insert()方法繞暈了。
append 和extend都只需要一個參數,並且自動添加到數組末尾,如果需要添加多個,可用數組嵌套,但是 append是將嵌套後的數組作為一個對象,
extend是將嵌套的數組內容作為多個對象,添加到原數組中
作為編程0基礎的小白,覺得有必要自己再梳理一遍:
1.append()方法是指在列表末尾增加一個數據項。
例如:在students列表末尾增加"Gavin"項。
1 2 3 4 |
>>>students = [‘Cleese‘ , ‘Palin‘ , ‘Jones‘ , ‘Idle‘]
>>> students.append(‘Gavin‘)
>>> print (students)
[‘Cleese‘, ‘Palin‘, ‘Jones‘, ‘Idle‘, ‘Gavin‘]
|
2.extend()方法是指在列表末尾增加一個數據集合。
例如:在例1基礎上,students列表末尾繼續增加"Kavin"與"Jack"和"Chapman"三項。
1 2 3 4 5 6 7 |
>>> students = [‘Cleese‘ , ‘Palin‘ , ‘Jones‘ , ‘Idle‘]
>>> students.append(‘Gavin‘)
>>> print (students)
[‘Cleese‘, ‘Palin‘, ‘Jones‘, ‘Idle‘, ‘Gavin‘]
>>> students.extend([‘Kavin‘,‘Jack‘,‘Chapman‘])
>>> print (students)
[‘Cleese‘, ‘Palin‘, ‘Jones‘, ‘Idle‘, ‘Gavin‘, ‘Kavin‘, ‘Jack‘, ‘Chapman‘]
|
3.insert()方法是指在某個特定位置前面增加一個數據項。
例如:在students原始列表中"Palin"前面增加"Gilliam"。
1 2 3 4 |
>>> students = [‘Cleese‘ , ‘Palin‘ , ‘Jones‘ , ‘Idle‘]
>>> students.insert( 1 , ‘Gilliam‘)
>>> print (students)
[‘Cleese‘, ‘Gilliam‘, ‘Palin‘, ‘Jones‘, ‘Idle‘]。
|
由於數據項自下而上堆放的,堆棧中的第一個數據編號為0,第二個數據編號為1,所以為students.insert(1, ‘Gillam‘)。