首页 > 代码库 > 列表的添加和删除

列表的添加和删除

Python 2.7.10 (default, Oct 14 2015, 16:09:02) [GCC 5.2.1 20151010] on linux2Type "copyright", "credits" or "license()" for more information.>>> assert 3>4Traceback (most recent call last):  File "<pyshell#0>", line 1, in <module>    assert 3>4AssertionError>>> assert 4>3>>> range(4,5)[4]>>> member=["nihao","hello"]>>> member[nihao, hello]>>> member[nihao, hello]>>> empty=[]>>> empty[]>>> a=["nihao",1,[2,3,4]]>>> a[nihao, 1, [2, 3, 4]]>>> num=[1,2,3]>>> num[1, 2, 3]>>> len(num)3>>> num.append(4) #插入元素>>> num[1, 2, 3, 4]>>> len(num)4>>> num.append("nizhi")>>> len(num)5>>> num[1, 2, 3, 4, nizhi]>>> num.append(5,6)  #不能插入两个元素Traceback (most recent call last):  File "<pyshell#19>", line 1, in <module>    num.append(5,6)TypeError: append() takes exactly one argument (2 given)>>> num.extend([5,6])  #用extend可以插入多个元素>>> num[1, 2, 3, 4, nizhi, 5, 6]>>> len(num)7>>> num.insert(0,10)  #在中间进行插入元素>>> num[10, 1, 2, 3, 4, nizhi, 5, 6]>>> len(num)8>>> num[0]10>>> num[5]nizhi>>> print(num[5])nizhi>>> tmp=num[0]>>> num[0]=num[7]>>> num[7]=tmp>>> num[6, 1, 2, 3, 4, nizhi, 5, 10]>>> len(num)8>>> num.remove("nizhi")  #删除>>> num[6, 1, 2, 3, 4, 5, 10]>>> member.remove(11)Traceback (most recent call last):  File "<pyshell#36>", line 1, in <module>    member.remove(11)ValueError: list.remove(x): x not in list>>> del num[0] # 删除某个>>> num[1, 2, 3, 4, 5, 10]>>> num.pop() #从最后删除,有返回值10>>> tmp=num.pop()#可以用变量来承接一下poop出来的返回值>>> tmp5>>> num.pop(0)1>>> num[2, 3, 4]>>> 

列表切片   [:]取出中间的某一段元素切片,如果不加上,默认就是边界

 1 >>> a=[1,2,3,4,5,6] 2 >>> a 3 [1, 2, 3, 4, 5, 6] 4 >>> a[1:3] 5 [2, 3] 6 >>> a[:4] 7 [1, 2, 3, 4] 8 >>> a[1:] 9 [2, 3, 4, 5, 6]10 >>> a[:]11 [1, 2, 3, 4, 5, 6]12 >>> tmp_a=a13 >>> tmp_a14 [1, 2, 3, 4, 5, 6]15 >>> tmp_b=a[:]16 >>> tmp_b17 [1, 2, 3, 4, 5, 6]18 >>> 

 

列表的添加和删除