当前位置 博文首页 > RunningOnMyWay的博客:Python3基础学习----元组

    RunningOnMyWay的博客:Python3基础学习----元组

    作者:[db:作者] 时间:2021-06-23 15:08

    1.元组创建

    创建只有一个元素的元组时一定要在后面加上“,”;

    >>> t = (1,2,3,"python")
    >>> t
    (1, 2, 3, 'python')
    >>> tuple(1,2,3)
    Traceback (most recent call last):
      File "<pyshell#3>", line 1, in <module>
        tuple(1,2,3)
    TypeError: tuple expected at most 1 argument, got 3
    >>> t2 = tuple([1,2,3,"pythons"])
    >>> t2
    (1, 2, 3, 'pythons')
    
    2.元素与列表区别
    1. 一个定义使用的符号不同元组为()  列表为[]
    2. 元组元素不可修改,不可添加也不可删除;列表可以插入修改
    
    3.元组的方法

    获取指定元素索引位置,以及获取元素个数

    >>> t2.index(1)
    0
    >>> t2.count(2)
    1
    
    4.元组值更改

    元组本身无法直接修改,可将其转为数组后更改

    >>> lis = list(t2)
    >>> lis
    [1, 2, 3, 'pythons']
    >>> lis.append("abcde")
    >>> lis
    [1, 2, 3, 'pythons', 'abcde']
    >>> t2 = tuple(lis)
    >>> t2
    (1, 2, 3, 'pythons', 'abcde')