下面的内容是网上一个博客中看到的,认为可以记录一下,首先感谢博主!
看到有关list方法append和extend的使用:
先看总结:
- append和extend都仅只可以接收一个参数
- append的参数类型任意,如上面所示的单个元素,list乃至元组都行
- extend的参数可以为单个元素,也可以包含有迭代器属性的list,元组
- append是把对象作为一个整体追加到list后面的,extend是把list或者元组的元素逐个加入到list中,也就是说append追加一个list或者元组的话,最后一个元素本身是一个list或者元组,而extend扩展一个list或者元组的话,list中的元素逐个加入,最后得到的是一个变长的list。
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或者元组。