标签:
List函数可以通过字符串来创建字符列表,如下面所示:
>>> list(‘Hello‘) [‘H‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘]
>>> x=[1,2,3] >>> x[1]=4 >>> x [1, 4, 3]
>>> x [1, 4, 3] >>> del x[1] >>> x [1, 3]
2.3分片赋值
>>> name=list(‘Perl‘) >>> name [‘P‘, ‘e‘, ‘r‘, ‘l‘] >>> name[2:] [‘r‘, ‘l‘] >>> name[2:]=list(‘ar‘) >>> name [‘P‘, ‘e‘, ‘a‘, ‘r‘]
>>> name [‘P‘, ‘e‘, ‘a‘, ‘r‘] >>> name[2:]=list(‘nsil‘) >>> name [‘P‘, ‘e‘, ‘n‘, ‘s‘, ‘i‘, ‘l‘] >>> name[1:1]=[1,2,3] >>> name [‘P‘, 1, 2, 3, ‘e‘, ‘n‘, ‘s‘, ‘i‘, ‘l‘] >>> name[1:1]=list(‘123‘) >>> name [‘P‘, ‘1‘, ‘2‘, ‘3‘, 1, 2, 3, ‘e‘, ‘n‘, ‘s‘, ‘i‘, ‘l‘] >>> name[1:4]=[] >>> name [‘P‘, 1, 2, 3, ‘e‘, ‘n‘, ‘s‘, ‘i‘, ‘l‘]
2.3append方法
>>> lst=[1,2,3] >>> lst.append(4) >>> lst [1, 2, 3, 4]
2.4count方法
>>> [‘sfdf‘,‘sfdf‘,‘sd‘,‘sd‘].count(‘sd‘) 2 >>> x=[[1,2],1,1,[2,1,[1,2]]] >>> x.count(1) 2
>>> a=[1,2,3] >>> b=[4,5,6] >>> a.extend(b) >>> a [1, 2, 3, 4, 5, 6] >>> b [4, 5, 6] >>> a+b [1, 2, 3, 4, 5, 6, 4, 5, 6] >>> a [1, 2, 3, 4, 5, 6] >>> a=a+b >>> a [1, 2, 3, 4, 5, 6, 4, 5, 6]
>>> knights=[‘we‘,‘are‘,‘the‘,‘knights‘,‘who‘,‘say‘,‘ni‘] >>> knights.index(‘who‘) 4 >>> knights[4] ‘who‘
>>> numbers=[1,2,3,4] >>> numbers.insert(0,‘aa‘) >>> numbers [‘aa‘, 1, 2, 3, 4]
>>> x=[1,2,3] >>> x.pop() 3 >>> x [1, 2] >>> x.pop(0) 1 >>> x [2] >>> x=[1,2,3] >>> x.append(x.pop()) >>> x [1, 2, 3] >>> x.pop(0) 1 >>> x.append(3) >>> x [2, 3, 3]
>>> x=[‘to‘,‘be‘,‘or‘,‘not‘,‘to‘,‘be‘] >>> x.remove(‘be‘) >>> x [‘to‘, ‘or‘, ‘not‘, ‘to‘, ‘be‘]
>>> x=[1,2,3] >>> x.reverse() >>> x [3, 2, 1]
>>> x=[2,1,4,3,2,5] >>> x.sort() >>> x [1, 2, 2, 3, 4, 5] >>> x=[2,1,4,3,2,5] >>> y=x[:] >>> y.sort() >>> x [2, 1, 4, 3, 2, 5] >>> y [1, 2, 2, 3, 4, 5] >>> x=[4,6,2,1,7,9] >>> y=sorted(x) >>> x [4, 6, 2, 1, 7, 9] >>> y [1, 2, 4, 6, 7, 9]
>>> x=[‘qq‘,‘dfsfd‘,‘ssfd‘,‘sdfdfffff‘] >>> x.sort(key=len) >>> x [‘qq‘, ‘ssfd‘, ‘dfsfd‘, ‘sdfdfffff‘] >>> x=[4,6,2,1,7,9] >>> x.sort(reverse=True) >>> x [9, 7, 6, 4, 2, 1]
所有注意点尽在代码之中,仔细体会实践一遍即可,python的列表操作十分强大。
标签:
原文地址:http://my.oschina.net/zzw922cn/blog/531856