标签:
列表定义
>>> a=[‘Free‘,‘1998‘] >>> type(a) <type ‘list‘> >>> bool(a) #列表有值,则为true True >>> print a [‘Free‘, ‘1998‘] >>>
索引和切片
>>> a=[‘Hello‘,‘World‘,‘2006‘] >>> a[1] ‘World‘ >>> a[1:2] [‘World‘] >>> a[-2:-1] [‘World‘]
list函数
>>> dir(list) [‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__delslice__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getslice__‘, ‘__gt__‘, ‘__hash__‘, ‘__iadd__‘, ‘__imul__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__reversed__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__setslice__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘append‘, ‘count‘, ‘extend‘, ‘index‘, ‘insert‘, ‘pop‘, ‘remove‘, ‘reverse‘, ‘sort‘]
appand 追加元素
>>> fruits=[‘orange‘,‘apple‘,‘banana‘]
>>> fruits.append(‘matermelon‘)
>>> fruits
[‘orange‘, ‘apple‘, ‘banana‘, ‘matermelon‘]
extend 合并两个list
>>> a=[1,2,3] >>> b=[4,5] >>> a.extend(b) >>> a [1, 2, 3, 4, 5]
extend 的对象是一个 list,如果是 str,则 Python 会先把它按照字符为单位转化为 list 再追加到已知 list
>>> la = [1,2,3] >>> b = "abc" >>> la.extend(b) >>> la [1, 2, 3, ‘a‘, ‘b‘, ‘c‘] >>> c = 5 >>> la.extend(c) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ‘int‘ object is not iterable
reverse 反转
方法1[::-1]
>>> a=[1,2,3] >>> a[::-1] [3, 2, 1] >>> a="python" >>> a[::-1] ‘nohtyp‘ >>>
方法2:list(reversed(list))
>>> a=[1,2,3] >>> list(reversed(a)) [3, 2, 1]
方法3:reverse
>>> a=[1,2,3] >>> a.reverse() >>> a [3, 2, 1]
count 统计某一个元素在list中出现的次数,如果没有则返回0
>>> c=[a,b,c,a,a] >>> c.count(a) 3
>>> c.count(‘f‘)
0
index 返回索引
>>> c=[a,b,c,a,a] >>> c.index(a) #第一次出现的位置 0
insert
list.insert(i, x) 中的 i 是将元素 x 插入到 list 中的位置,即将 x 插入到索引值是 i 的元素前面。注意,索引是从 0
>>> l=[‘a‘,‘b‘,‘c‘,‘d‘] >>> l.insert(1,‘#‘) >>> l [‘a‘, ‘#‘, ‘b‘, ‘c‘, ‘d‘]
如果i大于索引的最大值,那么就变成追加了
>>> a = [1,2,3] >>> a.insert(9,777) >>> a [1, 2, 3, 777]
remove
移除掉第一次匹配的元素
>>> lst=[‘a‘,‘b‘,‘a‘,‘c‘] >>> lst.remove(‘a‘) >>> lst [‘b‘, ‘a‘, ‘c‘]
pop
根据索引移除某一个元素
>>> lst=[‘a‘,‘b‘,‘a‘,‘c‘] >>> lst.pop(0) ‘a‘ >>> lst [‘b‘, ‘a‘, ‘c‘]
sort
默认情况,实现的是从小到大的排序。
>>> lst=[4,5,7,1,9] >>> lst.sort() >>> lst [1, 4, 5, 7, 9]
从大到小
>>> lst=[4,5,7,1,9] >>> lst.sort(reverse=True) >>> lst [9, 7, 5, 4, 1]
按照关键字排序
>>> lst = ["Python","java","c","pascal","basic"] >>> lst.sort(key=len) >>> lst [‘c‘, ‘java‘, ‘basic‘, ‘Python‘, ‘pascal‘]
标签:
原文地址:http://www.cnblogs.com/zydev/p/5838447.html