美文网首页
Python中的可变类型与不可变类型

Python中的可变类型与不可变类型

作者: XYZeroing | 来源:发表于2017-08-29 07:47 被阅读0次

    1.列表操作

    1.赋值  
    >>>ll = ['2', 'hello', 8.9, ['hahhah', 2]]
    >>> list_from_other = list('Hello Wrold!')
    >>> list_from_other
    ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'r', 'o', 'l', 'd', '!']
    
    2.访问
    >>> ll[0]
    '2'
    >>> ll[3]
    ['hahhah', 2]
    >>> ll[3][0]
    'hahhah'
    >>> ll[-3:-1]
    ['hello', 8.9]
    
    3.更新
    >>> ll[0]=1234567890
    >>> ll
    [1234567890, 'hello', 8.9, ['hahhah', 2]]
    >>> ll.append('This is a test!')
    >>> ll
    [1234567890, 'hello', 8.9, ['hahhah', 2], 'This is a test!']
    >>> l = ['string', 's', 56]
    >>> ll.extend(l)
    >>> ll
    [1234567890, 'hello', 8.9, ['hahhah', 2], 'This is a test!', 'string', 's', 56]
    
    4.删除
    >>> del ll[1]
    >>> ll
    [1234567890, 8.9, ['hahhah', 2], 'This is a test!', 'string', 's', 56]
    >>> ll.remove('This is a test!')
    >>> ll
    [1234567890, 8.9, ['hahhah', 2], 'string', 's', 56]
    >>> ll.pop(2)
    ['hahhah', 2]
    >>> ll
    [1234567890, 8.9, 'string', 's', 56]
    >>> ll.pop()
    56
    

    2.序列类型可用的内建函数

    >>> alist = [100, 3, 0, 34, 98, 33, 0.3, 54, 23]
    
    1.迭代
    >>> for item in alist:  #遍历元素
            print item
    
        
    100
    3
    0
    34
    98
    33
    0.3
    54
    >>> for i in range(len(alist)):   #对每个元素进行操作
            alist[i] * 2
    
        
    200
    6
    0
    68
    196
    66
    0.6
    108
    
    >>> for index, value in enumerate(alist): #同时返回index和list中的元素
            print index, value
    
        
    0 100
    1 3
    2 0
    3 34
    4 98
    5 33
    6 0.3
    7 54
    8 23
    
    >>> for i, j in zip(ll, l): #zip()参数可以是dict或tuple,同时输出多个,以最短的为主
            print i, j
    
        
    1234567890 string
    8.9 s
    string 56
    
    2.len()返回List长度
    >>> print len(alist)    
    9
    
    3.返回List中最大的元素
    >>> max(alist)   
    100
    
    4.返回List中最小的元素
    >>> min(alist)   
    0
    
    5.返回List中元素的和,只有List全部是数字才可以
    >>> sum(alist)    
    345.3
    
    6.sorted()方法返回排序号的序列,有字母时按照ASCⅡ码排序
    >>> print sorted(alist)    
    [0, 0.3, 3, 23, 33, 34, 54, 98, 100]
    
    7.reversed()方法不返回序列,返回一个迭代器
    >>> print reversed(alist)
    <listreverseiterator object at 0x0000000002053B38>
    >>> alist
    [100, 3, 0, 34, 98, 33, 0.3, 54, 23]
    

    3.序列操作符

    >>> alist = [100, 3, 0, 34, 98, 33, 0.3, 54, 23]
    
    1.成员判断符,'in'或者'not in '
    >>> 100 in alist
    True
    >>> 2 in alist
    False
    >>> 0  not in alist
    False
    
    2.切片'[::]'或者'[:]'  slice[n:m]开始的位置包括n,结束在m之前,类似左开右闭区间 [n,m)
    >>> alist[::2]
    [100, 0, 98, 0.3, 23]
    >>> alist[2:5:2]
    [0, 98]
    >>> alist[::-1]
    [23, 54, 0.3, 33, 98, 34, 0, 3, 100]
    
    3.重复操作符'*'  
    >>> ll = ['2', 'hello', 8.9, ['hahhah', 2]]
    >>> list1 = ll * 2
    >>> list1
    ['2', 'hello', 8.9, ['hahhah', 2], '2', 'hello', 8.9, ['hahhah', 2]]
    
    4.连接操作符'+'  
    >>> list2 = alist + ll
    >>> list2
    [100, 3, 0, 34, 98, 33, 0.3, 54, 23, '2', 'hello', 8.9, ['hahhah', 2]]
    
    

    4.列表类型内建函数

    
    list.append(obj)
    list.extend(seq)
    list.remove(obj)
    list.pop([index=-1])
    
    list.count(obj)返回一个obj在List中出现的次数
    >>> test_list
    [100, 3, 0, 34, 98, 33, 0.3, 54, 23, 3, 1234567890, 8.9, 'string', 's']
    >>> test_list.count(3)
    2
    
    list.index(obj, i=0, j=len(list)) 在i<=k<j之间返回list[k]==obj的k值
    >>> test_list.index(1234567890)
    10
    >>> test_list.index(3, 2, len(test_list)) #查找第二个3
    9
    
    list.sort()与list.reverse()无返回值
    >>> test_list.sort()
    >>> test_list
    [0, 0.3, 3, 3, 8.9, 23, 33, 34, 54, 98, 100, 1234567890, 's', 'string']
    >>> test_list.reverse()
    >>> test_list
    ['string', 's', 1234567890, 100, 98, 54, 34, 33, 23, 8.9, 3, 3, 0.3, 0]
    
    list.insert(index, value)插入元素
    >>> test_list.insert(2, 'import this')
    >>> test_list
    ['string', 's', 'import this', 1234567890, 100, 98, 54, 34, 33, 23, 8.9, 3, 3, 0.3, 0]
    

    5.列表解析

    列表解析的一般语法:[元素或者元素的操作 迭代(for) 条件(if)]

    >>> new_list = [x ** 2 for x in range(0, 10) if x % 2 == 0]
    >>> new_list
    [0, 4, 16, 36, 64]
    

    6.tuple

    tuple可以看做不能改变的list,一旦被定义,不可改变
    tuple的创建和访问与list一样,但是tuple不可更新,更新意味着创建新的tuple
    tuple不能删除一个元素,只能del atuple全部删除
    所有多对象的、逗号分隔的、没有明确用符号定义的,这些集合的默认类型都是tuple
    所有返回的多对象的都是元组类型

    7.用列表构建其他数据类型

    • stack:先入后出
    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    
    stack = []      #建立存储的stack
    
    #进栈
    def pushit():
        stack.append(raw_input("Please Enter your String : ").strip())
    
    #出栈
    def popit():
        if len(stack) == 0:
            print "Connot pop from an Empty Stack!"
        else:
            print "Romove [", `stack.pop()`,"] successful!"
    
    #观察栈
    def viewstack():
        print stack
    
    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()[0].lower()
                except (EOFError, KeyboardInterrupt, IndexError):
                    choice = 'q'
    
                print '\nYou 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()
    
    • 队列:先进先出
    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    
    queue = []
    
    # 进队列
    def enQ():
        queue.append(raw_input("Please Enter your String : ").strip())
    
    
    # 出队列
    def delQ():
        if len(queue) == 0:
            print "Connot pop from an Empty Queue!"
        else:
            print "Romove [", `queue.pop(0)`, "] successful!"  #pop()函数默认为index = -1
    
    
    # 观察队列
    def viewqueue():
        print queue
    
    
    CMDs = {'e': enQ, 'd': delQ, 'v': viewqueue}
    
    
    # 菜单
    def showmenu():
        pr = """
        (E)nterqueue
        (D)delqueue
        (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 '\nYou picked: [%s]' % (choice)
                if choice not in 'devq':
                    print 'Invalid option, try again'
                else:
                    break
            if choice == 'q':
                break
            CMDs[choice]()
    
    
    if __name__ == '__main__':
        showmenu()
    
    
    

    相关文章

      网友评论

          本文标题:Python中的可变类型与不可变类型

          本文链接:https://www.haomeiwen.com/subject/svgndxtx.html