美文网首页
Python之list与tuple

Python之list与tuple

作者: 射手再见蓝天575 | 来源:发表于2018-01-09 01:09 被阅读0次

    list

    • 列表的定义:

    列表是有序的,可变的一组数据的集合 ,它的声明如下:
    L = ['example',65,False]

    • 列表的索引:
    元素 A B C
    正索引 0 1 2
    负索引 -3 -2 -1
    >>> L = ['example',65,False]
    >>> L
    ['example', 65, False]
    >>> L[0]
    'example'
    >>> L[-3]
    'example'
    
    • 列表元素的添加:
      • 追加:append()
        >>> L.append("hello")
        >>> L
        ['example', 65, False, 'hello']
        
      • 插入:insert()
        >>> L.insert(2,'baby')
        >>> L
        ['example', 65, 'baby', False, 'hello']
        
    • 列表元素的删除:
      • 末尾删除:pop()
        >>> L
        ['example', 65, 'baby', False, 'hello']
        >>> L.pop()
        'hello'
        >>> L
        ['example', 65, 'baby', False]
        
      • 指定删除:pop(i)
        >>> L
        ['example', 65, 'baby', False]
        >>> L.pop(2)
        'baby'
        >>> L
        ['example', 65, False]
        
    • 列表元素的替换:索引+赋值
      >>> L
      ['example', 65, False]
      >>> L[1] = 99
      >>> L
      ['example', 99, False]
      
    • 列表的嵌套:
      >>> p=['father','mather']
      >>> L.append(p)
      >>> L
      ['example', 99, False, ['father', 'mather']]
      >>> L[3][1]
      'mather'
      >>> L[3][0]
      'father'
      

    tuple

    • 元组与列表的不同:
      • 元组的元素一旦初始化不可改变,这也导致了没有增添修改之类的函数。
      • 初始化用(),例如:
        t = (3,true)
      • 只有一个元素的声明:

        为避免t = (8)与数的赋值相冲突,tuple仅有1个元素的声明在后面加",": t = (8,)

    • 元组中嵌套列表:

    元组的元素不可改变,但嵌套在内的列表的元素可变,这并不违背元组的定义,因为元组的列表元素指向的是列表,列表地址不变则说明元组元素不变,只是列表的元素变了

     >>> T[2]
     ['father', 'mather']
     >>> T[2][1] = 'boy'
     >>> T
     ('hello', 'world', ['father', 'boy'])
    
    • 需要注意的是:

      可以通过直接改变内嵌列表的元素改变元组的元素值,但不能用初始化的方法改变列表的元素,那样的话,列表地址将发生变化

    >>> s = ['s','d']
    >>> S = ('f','g',s)
    >>> S
    ('f', 'g', ['s', 'd'])
    >>> id(s)
    93129704
    >>> id(S)
    56973872
    >>> id(S[2])
    93129704
    >>> s[1] = 'y'
    >>> id(s)
    93129704
    >>> s
    ['s', 'y']
    >>> S
    ('f', 'g', ['s', 'y'])
    >>> s = ['y','e']
    >>> id(s)
    93130304
    >>> S
    ('f', 'g', ['s', 'y'])
    

    相关文章

      网友评论

          本文标题:Python之list与tuple

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