最近,在閱讀Scrapy的源碼的時候,看到有關list方法append和extend的使用。初一看,還是有些迷糊的。那就好好找點資料來辨析一下吧。
stackoverflow中的回答是這樣的:
append:在尾部追加對象(Appends object at end)
C:\Users\sniper.geek>python2Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> x =[1,2,3]>>> x.append([4,5])>>> print x
[1, 2, 3, [4, 5]]>>>
對於append,是否可以只追加一個元素呢?試試看:
C:\Users\sniper.geek>python2Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> x=[1,2,3]>>> x.append(5)>>> print x
[1, 2, 3, 5]>>>
那是否可以追加一個元組呢?繼續試試:
C:\Users\sniper.geek>python2Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> x=[1,2,3]>>> x.append(5)>>> print x
[1, 2, 3, 5]>>> x.append((6,7,8))>>> print x
[1, 2, 3, 5, (6, 7, 8)]>>>
綜上可知,append可以追加一個list,還可以追加一個元組,也可以追加一個單獨的元素。
extend:通過從迭代器中追加元素來擴展序列(extends list by appending elements from the iterable)
C:\Users\sniper.geek>python2Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> x=[1,2,3]>>> x.extend([4,5])>>> print x
[1, 2, 3, 4, 5]>>>
那么,extend的參數是否可以為list或者元組呢?試一試:
C:\Users\sniper.geek>python2Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> x=[1,2,3]>>> x.extend([4,5,6])>>> print x
[1, 2, 3, 4, 5, 6]>>> x.extend((8,9,10))>>> print x
[1, 2, 3, 4, 5, 6, 8, 9, 10]>>>
綜上可知:extend的參數除了為單個元素,也可以為list或者元組。
總結:
- append和extend都僅只可以接收一個參數
- append的參數類型任意,如上面所示的單個元素,list乃至元組都行
- extend的參數可以為單個元素,也可以包含有迭代器屬性的list,元組
- append是把對象作為一個整體追加到list后面的,extend是把list或者元組的元素逐個加入到list中,也就是說append追加一個list或者元組的話,最后一個元素本身是一個list或者元組,而extend擴展一個list或者元組的話,list中的元素逐個加入,最后得到的是一個變長的list。