最近,在阅读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或者元组。
总结: