Python List中的append和extend

      最近,在閱讀Scrapy的源碼的時候,看到有關list方法append和extend的使用。初一看,仍是有些迷糊的。那就好好找點資料來辨析一下吧。python

      stackoverflow中的回答是這樣的:app

      append:在尾部追加對象(Appends object at end)spa

C:\Users\sniper.geek>python2
Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> x =[1,2,3]
>>> x.append([4,5])
>>> print x
[1, 2, 3, [4, 5]]
>>>

      對於append,是否能夠只追加一個元素呢?試試看:orm

C:\Users\sniper.geek>python2
Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win
32
Type "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>python2
Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win
32
Type "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,還能夠追加一個元組,也能夠追加一個單獨的元素。ip

      extend:經過從迭代器中追加元素來擴展序列(extends list by appending elements from the iterable)element

C:\Users\sniper.geek>python2
Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win
32
Type "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>python2
Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win
32
Type "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或者元組。it

      總結:       io

  1. append和extend都僅只能夠接收一個參數      
  2. append的參數類型任意,如上面所示的單個元素,list乃至元組都行      
  3. extend的參數能夠爲單個元素,也能夠包含有迭代器屬性的list,元組      
  4. append是把對象做爲一個總體追加到list後面的,extend是把list或者元組的元素逐個加入到list中,也就是說append追加一個list或者元組的話,最後一個元素自己是一個list或者元組,而extend擴展一個list或者元組的話,list中的元素逐個加入,最後獲得的是一個變長的list。
相關文章
相關標籤/搜索