Python extend 和 append 的區別
阿新 • • 發佈:2018-02-02
module eba back -- def object ror int iterable
在python中,關於list添加元素的操作有兩個方法,即extend和append。但兩者的用法還是存在一些區別:
1.append可以添加單個元素,也可以添加可叠代對象,但是extend只能添加可叠代對象:
arr = [1,2,3,4] In [155]: arr.append(5) In [156]: arr Out[156]: [1, 2, 3, 4, 5] In [157]: arr_1 = [1,2,3,4] In [158]: arr_1.extend(5) --------------------------------------------------------------------------- TypeError Traceback (most recent call last)<ipython-input-158-a5e15af180e0> in <module>() ----> 1 arr_1.extend(5) TypeError: ‘int‘ object is not iterable
2.在添加可叠代對象是,append在添加後不改變添加項的類型,添加之前是什麽類型,添加之後就是什麽類型;而extend在添加後,會將添加項進行叠代,叠代的元素挨個添加到被添加的數組中:
arr_ap = [1,2,3,4] item = [5,6,7] arr_ap.append(item) In [160]: arr_ap Out[160]: [1, 2, 3, 4, [5, 6, 7]] In [161]: arr_ex = [1,2,3,4] item = [5,6,7] arr_ex.extend(item) In [162]: arr_ex Out[162]: [1, 2, 3, 4, 5, 6, 7]
用一個更具體的栗子,使用遞歸叠代置換一個數組,使用同樣的算法,變的只是添加元素的時候,分別用append和extend,大家應該可以從打印的結果看出明顯的區別了:
使用append:
def testF1(n): a = [] i = 0 val = n[i] del n[i] a.append(val)if len(n) != 0: i + 1 a.append(testF1(n)) else: print(‘end‘) return a In [164]: c = testF1([3,2,5,1]) c end Out[164]: [3, [2, [5, [1]]]]
使用extend:
def testF1(n): a = [] i = 0 val = n[i] del n[i] a.append(val) if len(n) != 0: i + 1 a.extend(testF1(n)) else: print(‘end‘) return a In [166]: c = testF1([3,2,5,1]) c end Out[166]: [3, 2, 5, 1]
Python extend 和 append 的區別