Python List中的append和extend

來源:互聯網
上載者:User

標籤:

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

      stackoverflow中的回答是這樣的:

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

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,是否可以只追加一個元素呢?試試看:

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,還可以追加一個元組,也可以追加一個單獨的元素。

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

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或者元組。

      總結:      

  1. append和extend都僅只可以接收一個參數      
  2. append的參數類型任意,如上面所示的單個元素,list乃至元組都行      
  3. extend的參數可以為單個元素,也可以包含有迭代器屬性的list,元組      
  4. append是把對象作為一個整體追加到list後面的,extend是把list或者元組的元素逐個加入到list中,也就是說append追加一個list或者元組的話,最後一個元素本身是一個list或者元組,而extend擴充一個list或者元組的話,list中的元素逐個加入,最後得到的是一個變長的list。

Python List中的append和extend

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.