• python 元组


    1.创建元组

    >>> tuple = (1,2,3,4,5)
    >>> tuple
    (1, 2, 3, 4, 5)
    View Code

    2.访问元组

    >>> tuple = (1,2,3,4,5)
    >>> tuple
    (1, 2, 3, 4, 5)
    >>> tuple[1:3]
    (2, 3)
    View Code

    3.注意:如果创建的元祖只有一个元素,请在元素后面加上逗号

    >>> tup = ()
    >>> tup1 = (1)
    >>> tup2 = (1,)
    >>> type(tup)
    <class 'tuple'>
    >>> type(tup1)
    <class 'int'>
    >>> type(tup2)
    <class 'tuple'>
    View Code

    4.元组修改

    4.1:元组内元素不可修改

    >>> tup = (1,'zc','cc','2','gg')
    >>> tup[1] = 2
    Traceback (most recent call last):
      File "<pyshell#103>", line 1, in <module>
        tup[1] = 2
    TypeError: 'tuple' object does not support item assignment
    View Code

    4.2:只可删除整个元组

    >>> tup = (1,'zc','cc','2','gg')
    >>> del tup[1]
    Traceback (most recent call last):
      File "<pyshell#105>", line 1, in <module>
        del tup[1]
    TypeError: 'tuple' object doesn't support item deletion
    >>> del tup
    >>> tup
    Traceback (most recent call last):
      File "<pyshell#107>", line 1, in <module>
        tup
    NameError: name 'tup' is not defined
    View Code

    4.3:修改元组内部,须切片拷贝

    >>> temp = ('小鸡','小猪','小鸭','小狗')
    >>> temp[:2] + ('通过切片增加一个元素',) + temp[2:]
    ('小鸡', '小猪', '通过切片增加一个元素', '小鸭', '小狗')
    View Code
    >>> temp = ('小鸡','小猪','小鸭','小狗')
    >>> temp[:1] + temp[2:]
    ('小鸡', '小鸭', '小狗')
    View Code

    4.4:用del删除整个元组

    >>> temp = ('小鸡','小猪','小鸭','小狗')
    >>> del temp
    >>> temp
    Traceback (most recent call last):
      File "<pyshell#123>", line 1, in <module>
        temp
    NameError: name 'temp' is not defined
    View Code

    5.元组的方法

    5.1:count  统计元素在列表中出现的次数

    >>> temp = ('小鸡','小猪','小鸭','小狗','小狗')
    >>> temp.count('小狗')
    2
    >>> temp.count('小鸡')
    1
    View Code

    5.2:index()   查到元素在列表中的位置

    >>> temp = ('小鸡','小猪','小鸭','小狗','小狗')
    >>> temp.index('小猪')
    1
    View Code
  • 相关阅读:
    MySQL主从数据库同步延迟问题解决(转)
    Python2.6升级Python2.7
    Socket网络编程
    Python 面向对象进阶
    Python类基础知识(面向对象基础)
    shell脚本中出现^M
    Centos6下Python3的编译安装
    Python成长之路(常用模块学习)
    SVN使用总结
    xshell锁屏
  • 原文地址:https://www.cnblogs.com/zjl-001/p/9575734.html
Copyright © 2020-2023  润新知