列表的常见方法:
对象.方法(参数)
1、追加(append)
>>> lst = [1,2,3] >>> lst.append(4) >>> lst [1, 2, 3, 4]
2、计数(count)
>>> list('helloworld') ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'] >>> string = list('helloworld') >>> string ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'] >>> string.count('o') 2 >>> x = [[1,2],1,2,[2,1,[1,2]]] >>> x.count(1) 1 >>> x.count([1,2]) 1
3、扩展(extend)
>>> a= ['hello'] >>> b= ['world'] >>> a.extend(b) >>> a ['hello', 'world'] >>> a+b ['hello', 'world', 'world'] >>> a ['hello', 'world']
4、返回索引位置(index)
>>> str = 'hello' >>> str.index('e') 1 >>> str.index('el') 1
5、插入(insert)
>>> numbers = [1,2,3,4,5,6,7] >>> numbers.insert(3,'four') >>> numbers [1, 2, 3, 'four', 4, 5, 6, 7]
6、出栈(pop)
>>> x = [1,2,3] >>> x.pop() 3 >>> x [1, 2] >>> x.pop(0) 1 >>> x [2]
7、移除第一个匹配项(remove)
>>> str = list('hello') >>> str ['h', 'e', 'l', 'l', 'o'] >>> str.remove('l') >>> str ['h', 'e', 'l', 'o']
8、求反(reverse)
>>> x [1, 2, 3, 4] >>> x.reverse() >>> x [4, 3, 2, 1]
9、排序(sort)
>>> x= [4,6,2,1,7,0] >>> y = x[:] >>> y.sort() >>> x [4, 6, 2, 1, 7, 0] >>> y [0, 1, 2, 4, 6, 7]
10、高级排序(cmp,key,reverse等作为参数提供给sort)
compare(x,y)当想x<y时返回负数、x>y时返回正数,x=y时返回0
>>> cmp(42,32) 1 >>> cmp(99,100) -1 >>> cmp(10,10) 0 >>> numbers = [5,2,7,9] >>> numbers.sort(cmp) >>> numbers [2, 5, 7, 9]
关键字key是可选参数,提供一个函数作为sort的依据
>>> x = ['aardvark','abalone','acme','add','aerate'] >>> x.sort(key=len) >>> x ['add', 'acme', 'aerate', 'abalone', 'aardvark']
关键字reverse也是可选参数,指定列表是否要逆反排序
>>> x= [4,6,2,1,7,9] >>> x.sort(reverse=True) >>> x [9, 7, 6, 4, 2, 1] >>> x.sort(reverse=False) >>> x [1, 2, 4, 6, 7, 9]