1.列表中的元素操作
(1)列表添加元素>>> aList = [1, 2 ,3] //定义列表,其中有3个成员
>>> aList.append(4) //使用append方法将4追加进去
>>> aList //查看追加情况
[1, 2, 3, 4]
>>> aList[1:3] = [20, 30, 40, 50] //在第2个和第3个成员之间追加这四个数,并且替换边上的两个数
>>> aList
[1, 20, 30, 40, 50, 4] //查看已经替换并增加
>>> aList[3:3] = ["a","b"] //在30和40之间增加这两个元素
>>> aList //查看增加后的情况
[1, 20, 30, 'a', 'b', 40, 50, 4]
>>> aList[3:3] //这么写中间就是空白,在空白插入
[]
>>> aList.extend(12345)
Traceback (most recent call last):
File "", line 1, in
TypeError: 'int' object is not iterable
>>> aList.extend("12345")
>>> aList
[3, 1, 5, '1', '2', '3', '4', '5']
>>> aList.extend("abc") //将列表中的每一个元素追加进去
>>> aList
[3, 1, 5, '1', '2', '3', '4', '5', 'a', 'b', 'c']
>>> aList.extend(("i","love","you"))
>>> aList
[3, 1, 5, '1', '2', 'i', 'love', 'you'] //如果需要将字符整体加进去,则加圆括号
(2)列表删除元素>>> aList
[1, 20, 30, 'a', 'b', 40, 50]
>>> aList.pop(4) //把b给删除掉,通过下标删除
'b'
>>> aList
[1, 20, 30, 'a', 40, 50]
>>> aList[5:5]=[50] //在40和50之间增加50这个元素
>>> aList
[1, 20, 30, 'a', 40, 50, 50]
>>> aList.remove(50) //移除掉所有的50
>>> aList
[1, 20, 30, 'a', 40, 50]
>>>
(3)拼接、重复操作、in 、not in>>> aList //查看列表
[1, 2, 3]
>>> aList + ["i love you"] //拼接,但是并没有写进去
[1, 2, 3, 'i love you']
>>> aList
[1, 2, 3]
>>> aList *2 //重复操作,同样没有写进去
[1, 2, 3, 1, 2, 3]
>>> aList
[1, 2, 3]
>>> 1 in aList //in 在里边为真
True
>>> 1 not in aList //not in 不在里边为真
False
2、常用的函数
(1)enumerate,可以将下标和对应的元素都列出来>>> aList
[1, 2, 3]
>>> for i ,j in enumerate(aList):
... print "#%s: %s" % (i, j)
...
#0: 1
#1: 2
#2: 3
(2)sum求和>>> sum(aList)
6
(3)zip将列表中的值取出来放到元组里>>> zip(aList)
[(1,), (2,), (3,)]
>>> zip(enumerate(aList))
[((0, 1),), ((1, 2),), ((2, 3),)]
(4)len,max,min,sorted函数也是常用函数>>> aList = [3, 1, 5]
>>> max(aList)
5
>>> min(aList)
1
>>> len(aList)
3
>>> sorted(aList)
[1, 3, 5]
3、内建函数
(1)count统计里边有多少个>>> aList = [3, 1, 5]
>>> aList.count(2)
0
>>> aList.count(3)
1
(2)index返回下标>>> aList.index("love")
12
>>> aList.index("i")
11
(3)insert可以在下标位置插入元素>>> aList
[1, 2, 3]
>>> aList.insert(1,"i love you") //在下标为1的地方插入i love you
>>> aList
[1, 'i love you', 2, 3]
(4)reverse原地翻转>>> aList
[1, 'i love you', 2, 3]
>>> aList.reverse()
>>> aList
[3, 2, 'i love you', 1]
(5)sort排序>>> aList
[3, 2, 'i love you', 1]
>>> aList.sort()
>>> aList
[1, 2, 3, 'i love you']
(6)shuffle打乱顺序>>> aList
[1, 2, 3, 'i love you'
>>> import random
>>> random.shuffle(aList)
>>> aList
[3, 'i love you', 1, 2]
4.脚本实例:模拟入栈出栈操作#!/usr/bin/env python
stack = []
def pushit():
data = raw_input("input your char: ")
stack.append(data)
def popit():
if stack:
print "popped char:", stack.pop()
else:
print "Empty char"
def viewit():
print stack
CMDs = {'1': pushit, '2': popit, '3': viewit}
def show_menu():
prompt = """(1)pushit
(2)popit
(3)viewit
(0)quit
please input your choice(0/1/2/3): """
while True:
choice = raw_input(prompt).strip()[0]
if choice not in "0123":
print "Invalid choice,try again"
continue
if choice == "0":
break
CMDs[choice]()
if __name__ == "__main__":
show_menu()