[入门-1]基础类型之列表

来源:互联网 发布:xp网络打印机安装步骤 编辑:程序博客网 时间:2024/06/01 07:33

基础操作

#createaList = [123, 'abc', [123, 4.45, 'hello'], 7-9j]bList = []list('foo')#accessaList[0]aList[2][1]aList[0:2]#remove add delete[].append()[].remove()del aList[1]del aList

操作符

#compare><==#切片, same as 序列类型操作符#成员关系123 in aList'abc' not in aList#连接操作符+list.extend()#重复操作符*aList*2#列表解析[i for i in range(8) if i%2 ==  0]   [0, 2 ,4, 6][exp for var in [] if var_exp]

内建函数

#标准类型内建函数cmp(list1,list2)#序列内建函数len()max()/min()sorted()  #字典序,ASCII序reversed()enumerate()for i, item in enumerate(aList)    print i, itemzip()for i,j in zip(aList,bList)    print ('%s %s' % (i, j)).title()sum(aList)sum(aList,5)reduce(operator.add, aList)anotherList = list(aTuple)anotherTuple = tuple(aList)[id(x) for x in aList, aTuple, anotherList, anotherTuple]

列表类型内建函数

dir(list)dir([])list.append(obj)   #add at taillist.count(obj)    #返回obj出现的次数list.extend(seq)   #原地,序列seq/可迭代对象的内容加入listlist.index(obj,i=0,j=len(list)) #返回list[key]==obj的key值,key范围可以选定#Notice index之前先用in来判断是否在列表中,否则index会返回异常list.insert(index,obj)          #索引位置插入objlist.pop(index=-1)              #删除并返回指定对象list.remove(obj)                #删除objlist.reverse()                  #原地,翻转列表list.sort(func=None,key=None,reverse=False) #原地排序#Notice,原地的意思是无返回值

example

#!/usr/bin/pythonstack = []def pushit():    passdef popit():    passdef viewstack():    passCMDs={'u':pushit, 'o':popit, 'v':viewstack}def showmenu():    pr='''    p(U)sh    p(O)p    (V)iew    (Q)uit    Enter choice:'''    while True:        while True:            try:                choice = raw_input(pr).strip().lower()            except (EOFError, KeyboardInterrupt, IndexError):                choice = 'q'            print '\n You picked: [%s]' % choice            if choice not in 'uovq'                print 'Invalid option, try again'            else:                break        if choice == 'q'            break        CMDs[choice]()if __name__ == '__main__'    showmenu()

Reference

Python核心编程

0 0