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

时间:2022-12-23 15:44:10

基础操作

#create
aList = [123, 'abc', [123, 4.45, 'hello'], 7-9j]
bList = []
list('foo')
#access
aList[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, item
zip()
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 tail
list.count(obj)    #返回obj出现的次数
list.extend(seq)   #原地,序列seq/可迭代对象的内容加入list

list.index(obj,i=0,j=len(list)) #返回list[key]==obj的key值,key范围可以选定
#Notice index之前先用in来判断是否在列表中,否则index会返回异常
list.insert(index,obj)          #索引位置插入obj
list.pop(index=-1)              #删除并返回指定对象
list.remove(obj)                #删除obj
list.reverse()                  #原地,翻转列表
list.sort(func=None,key=None,reverse=False) #原地排序
#Notice,原地的意思是无返回值

example

#!/usr/bin/python

stack = []
def pushit():
    pass
def popit():
    pass
def viewstack():
    pass

CMDs={'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核心编程