Python List中的append和extend


      最近,在閱讀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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM