python之序列之列表

上一篇 / 下一篇  2013-10-17 16:10:01 / 个人分类:python

#序列2:列表,元组
#1、列表:包含不同类型的对象,可执行的操作:pop,empt,sort,reverse操作,对单个元素可执行insert,update,remove操作
    #创建一个列表
alist = ['zhaoyehong','you are','the','first',1]
alist2 = []  #空list
alist3 = ['zhaoyehong',['you are','the'],'first',1]  #包含了一个list
print alist3
print list('zhaoyehong')  #将字符串转换为list:['z', 'h', 'a', 'o', 'y', 'e', 'h', 'o', 'n', 'g']
    #访问list
print alist[0]
print alist[1:3]  #列表的切片方法同于string
print alist3[1][1]   #访问的是alist3的第二个元素的第二个数 the
    #更新list:列表是可变的,可以通过赋值来更新,也可以通过追加的方式更新append(),extend()
alist[2] = 'xuximing'
print alist
alist.append('wo will get together well')   #append()方法会追加到alist后面
print alist                     #['zhaoyehong', 'you are', 'xuximing', 'first', 1, 'wo will get together well']
alist.extend('hello')           #['zhaoyehong', 'you are', 'xuximing', 'first', 1, 'wo will get together well', 'h', 'e', 'l', 'l', 'o']
print alist
    #删除元素
del alist[1]
print alist
alist.remove('zhaoyehong')
print alist               #['xuximing', 'first', 1, 'wo will get together well', 'h', 'e', 'l', 'l', '
print alist.pop(5)        #pop()删除方式会返回被删除的值 :e
del alist3              #删除整个列表
#print alist3            #NameError: name 'alist3' is not defined
    #标准类型操作符
list1 = ['abc',12]
list2 = ['e',12]
print list1 < list2      #输出True
    #序列操作符:切片[:12][:]同于strng
list3 = [4,[4,24],'zag','34d','erwe']
print list3[1]
list3[1][1] = 'zhaoyehong'      #将列表中的某个元素列表中的某个值赋值
print list3
list3[2:4] = ['zzz','xxx']      #将某个切片分别赋值
print list3                         
list3[0] = ['aa','bb','cc']     #将列表某个元素赋值列表
print list3

    #成员操作符
list4 = [4,[4,24],'zag','34d','erwe']
print 'zag' in list4    #zag是属于列表的
print 24 in list4       #False
print 24 in list4[1]   #True  ,24是属于列表的第二个元素中的第二个值
    #连接操作符
alist = ['zhaoyehong','you are','the','first',1]
alist2 = []  #空list
alist3 = ['zhaoyehong',['you are','the'],'first',1]
print alist + alist3        #输出两个列表连接的结果,这是新建了一个列表。不推荐使用
    #重复操作
print alist*2

    #列表解析
print [i*2 for i in [8,9,19]]
print [i for i in range(10) if i %2 ==0]
    #内建函数
    #cmp(str1,str2):对列表的元素做比较:1、同类型的,比较其值,返回结果 2、如果一方为数字,则另一个元素大(因为数字是最小的) 3、如果都为数字,进行强制类型转化为数字再进行比较 4、进行类型的字母顺序进行比较
                   #str1 >str2 返回1   ,str1 < str2 返回-1   ,相等返回0
str1 ,str2 ,str3 = ['a','b'],['a','b'],['b','b']
print cmp(str1,str2)
print cmp(str1,str3)
    #len(list)  :返回list的长度
alist3 = ['zhaoyehong',['you are','the'],'first',1]
print len(alist3)   #返回4
    #max(),min()函数返回列表中的最大值,最小值 sorted()排序,reversed(),将列表反向abc——》cba
print max(alist3)
print min(alist3)
print sorted(alist3)        #排序是使用的字典序,而不是字母序,字母序的'T'的acsii值比a还要靠前
print [i for i in reversed(alist3)]
list1 = ['a','b','c']
list2 = [1,2,3]
for a,b in enumerate(list1):print a,b   #enumerate()接受一个迭代参数,返回索引和值得tuple
for i,j in zip(list1,list2):print ('%s %s'%(i,j))
print sum(list2)
    #list(),tuple():两者可以完成list和tuple之间的转换
print tuple(list2)
tuple1 = (1,2,3,4)
print list(tuple1)
alist = list(tuple1)
print alist == tuple1  #False   :虽然他们的值显示的是一样的,但是一个list永远不能等于一个tuple
music_media = [45]
music_media.insert(0,'compact disc')
print music_media
music_media.append('long playing record')
print music_media
music_media.insert(2,'8-track tape')
print music_media
print 'aa' in music_media
print music_media.index('compact disc')
music = ['author','sing']
music_media.extend(music)   #['compact disc', 45, '8-track tape', 'long playing record', 'author', 'sing']
print music_media
music_media.append(music)   #['compact disc', 45, '8-track tape', 'long playing record', 'author', 'sing', ['author', 'sing']]
print music_media

#利用列表模仿堆栈
stack = []
def push():
    a = raw_input('please enter a new string:').strip()
    stack.append(a)
def pop():
    if len(stack) < 0:
        print 'cannot pop from an empty stack'
    else :
        print 'remove[',`stack.pop()`,']'
def view():
    print stack
CMDs = {'u':push,'o':pop,'v':view}
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()[0].lower()
            except (EOFError,KeyboardInterrupt,IndexError):
                choice = 'q'
            print '\n you picked[%s]'%choice
            if choice not in 'uovq':
                print 'invalid optin,try again'
            else:
                break
        if choice == 'q':
            break
        CMDs[choice]()
if __name__ == '__main__':
    showmenu()

#利用列表模仿队列
queue = []
def enQ():
    a = raw_input('please enter a new string:').strip()
    queue.append(a)
def deQ():
    if len(queue) < 0:
        print 'cannot pop from an empty stack'
    else :
        print 'remove[',`queue.pop(0)`,']'
def view():
    print queue
CMDs = {'e':enQ,'d':deQ,'v':view}
def showmenu():
    pr = '''
    (E)nqueue
    (D)equeue
    (V)iew
    (Q)uit
    Enter choice:
    '''
    while True:
        while True:
            try :
                choice = raw_input(pr).strip()[0].lower()
            except (EOFError,KeyboardInterrupt,IndexError):
                choice = 'q'
            print '\n you picked[%s]'%choice
            if choice not in 'edvq':
                print 'invalid optin,try again'
            else:
                break
        if choice == 'q':
            break
        CMDs[choice]()
if __name__ == '__main__':
    showmenu()    


TAG:

 

评分:0

我来说两句

日历

« 2024-04-29  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 15381
  • 日志数: 25
  • 建立时间: 2013-07-27
  • 更新时间: 2013-10-22

RSS订阅

Open Toolbar