-
append:在列表末尾追加1个新的对象
-
count:统计某个元素在列表中出现的次数
-
extend:在列表末尾一次性追加另一个序列中的多个值
例子:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a=[1,2,3] 4 a.append(4) 5 print a 6 b=['to','be','or','not','to','be'] 7 print b.count('to') 8 b1=[[1,2],1,1,[2,1,[1,2]]] 9 print b1.count(1) 10 print b1.count([1,2]) 11 print b1.count([2,1]) 12 c=[1,2,3] 13 c1=[4,5,6] 14 c.extend(c1) 15 print c
效果:
1 [1, 2, 3, 4]
2 2
3 2
4 1
5 0
6 [1, 2, 3, 4, 5, 6]
小知识:
方法后面是(),可以是b.count(1),但不能是b.count[1];
如果调用列表对象,则是([ ]),如:count([1,2])
index是找出某个值第一个匹配项的索引位置,不能进行赋值操作,如:d1.index(3)='king';
insert用于将对象插入到列表中,也不能进行赋值操作,如:d1.index(3)='Champion';可以使用d1.index(3,'Champion');
sort没有返回值,不能用f1=f.sort(cmp),只能用f.sort(cmp);sorted()函数可以使用赋值;
后面几个方法案例:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #1.append 4 a=[1,2,3] 5 a.append(4) 6 print a 7 #2.count 8 b=['to','be','or','not','to','be'] 9 print b.count('to') 10 b1=[[1,2],1,1,[2,1,[1,2]]] 11 print b1.count(1) 12 print b1.count([1,2]) 13 print b1.count([2,1]) 14 #3.extend 15 c=[1,2,3] 16 c1=[4,5,6] 17 c.extend(c1) 18 print c 19 c3=[1,2,3] 20 c4=[4,5,6] 21 c5=c3+c4 22 print c3 23 print c5 24 #4.index 25 d1=['we','are','the','knights','who','say','ni'] 26 d2=d1.index('who') 27 d3=d1.index('knights') 28 print d2 29 print d3 30 #5.insert 31 d1.insert(3,'Champion') 32 print d1 33 #6.pop 34 d4=d1.pop() 35 print d1 36 d5=d1.pop(4) 37 print d1 38 #7.remove 39 d1.remove('who') 40 d1.remove('say') 41 print d1 42 #8.reverse 43 d1.reverse() 44 print d1 45 #9.sort 46 e=[4,6,2,1,7,9] 47 e.sort() 48 print e 49 e=[4,6,2,1,7,9] 50 e1=e 51 e1.sort() 52 print e1 53 e=[4,6,2,1,7,9] 54 e2=e[:] 55 e2.sort() 56 print e2 57 e=[4,6,2,1,7,9] 58 e3=sorted(e) 59 print e3 60 #10.advence sort 61 f=[5,2,9,7] 62 f.sort(cmp) 63 print f 64 f2=['we','will','rock','you'] 65 f2.sort(key=len) 66 print f2 67 f.sort(reverse=True) 68 f2.sort(reverse=True) 69 print f 70 print f2 71 f3=['we','will','rock','you'] 72 f3.sort(reverse=True) 73 print f3
效果:
1 [1, 2, 3, 4] 2 2 3 2 4 1 5 0 6 [1, 2, 3, 4, 5, 6] 7 [1, 2, 3] 8 [1, 2, 3, 4, 5, 6] 9 4 10 3 11 ['we', 'are', 'the', 'Champion', 'knights', 'who', 'say', 'ni'] 12 ['we', 'are', 'the', 'Champion', 'knights', 'who', 'say'] 13 ['we', 'are', 'the', 'Champion', 'who', 'say'] 14 ['we', 'are', 'the', 'Champion'] 15 ['Champion', 'the', 'are', 'we'] 16 [1, 2, 4, 6, 7, 9] 17 [1, 2, 4, 6, 7, 9] 18 [1, 2, 4, 6, 7, 9] 19 [1, 2, 4, 6, 7, 9] 20 [2, 5, 7, 9] 21 ['we', 'you', 'will', 'rock'] 22 [9, 7, 5, 2] 23 ['you', 'will', 'we', 'rock'] 24 ['you', 'will', 'we', 'rock']
小知识:
对于数字用f.sort(reverse=True),顺序反过来了;对于字符串不行,原因还未找出,还在测试。。。