1、列表对象的方法2、用列表实现堆栈
1、列表对象的方法list.append(x)
添加元素(在列表尾端)
>>> list = [] >>> list.append(1)
list.extend(iterable)
用可迭代对象的元素(列表或可迭代函数)扩展列表
>>> list = [] >>> list.extend(range(1,5)) >>> list.extend([1,2,3,4])
list.inser(x,val)
指定下标插入元素
>>> list.extend([1,2,3,4]) >>> list.insert(2,7) >>> list [1, 2, 7, 3, 4] >>> list.insert(7,4) >>> list [1, 2, 7, 3, 4, 4] >>> list.insert(-1,4) >>> list [1, 2, 7, 3, 4, 4, 4] >>>
注意:下标超出列表本身长度很多,并没有报错,依旧添加了元素
list.remove(x)
从列表中移除第一个值为x的元素
>>> list.remove(1)
list.pop(x)
从列表中删除指定位元素,会返回删除值
>>> list = [] >>> list.extend(range(5)) >>> list [0, 1, 2, 3, 4] >>> list.pop(1) 1 >>> list.pop(2) 3 >>> list [0, 2, 4] >>>
也可以不指定,默认从尾部删除
>>> list2 [7, 6, 5, 4, 3, 2, 1] >>> list2.pop() 1 >>>
list.clear()
删除链表全部元素即清空列表
>>> list [0, 2, 4] >>> list.clear() >>> list [] >>>
list.index(x,[,start[,end]])
返回列表第一个值为x的元素下标
>>> list.extend(range(5)) >>> list [0, 1, 2, 3, 4] >>> list.index(2) #在整个列表下找 2 >>> list.index(3,0,3) #在0-3的下标找(注意:不包括3) Traceback (most recent call last): File "", line 1, in ValueError: 3 is not in list >>> list.index(3,0,4) 3 >>>
list.count(x)
返回列表中的x出现的次数
>>> list = [1,2,3,1,4,1,5] >>> list.count(1) 3 >>>
list.sort()
对列表进行排序,默认从小到大,但不是所有的数据和都可以排序
>>> list.sort() >>> list [1, 2, 3, 4, 5, 6, 7] >>>
list.reverse()
翻转列表中的元素
>>> list = [1,3,2,7,4,6,5] >>> list.sort() >>> list [1, 2, 3, 4, 5, 6, 7] >>> list.reverse() >>> list [7, 6, 5, 4, 3, 2, 1] >>>
list.copy()
返回列表的浅拷贝
>>> list [7, 6, 5, 4, 3, 2, 1] >>> list2 = list.copy() >>> list2 [7, 6, 5, 4, 3, 2, 1] >>>2、用列表实现堆栈
实现堆栈很简单,了解堆栈后进先出的特性,再借助列表对象方法append()方法添加元素,pop()方法取出元素,配合使用即可
>>> stack = [1,2,3] >>> stack.append(4) >>> stack.pop()
实现队列,首先依据队列先进先出的特性,在Python中使用列表实现效率低,但是用Collections类下的deque可以快速从两端添加/删除元素,deque是双向对列
>>> from Collections import deque
>>> queue = deque([1,2,3,4,5])
>>> queue.append('d')#添加元素
>>> queue.popleft() #头取出



