zoukankan      html  css  js  c++  java
  • 05-01元组

    元组

    特性:

    • 元组的最大特性是不可变。
    • 不可变意味着可hash, 意味着可以做字典的key, 可以做set的元素。
    • 函数时,元组的作用更强大。

    元组对象操作

    针对元组对象本身做的操作

    新建元组

    方法1:t = tuple()
    方法2:t = ()
    方法3:t = (1, 2, 3) # 直接赋值
    方法4:t = tuple(range(3))

    删除元组对象

    需要使用del方法删除
    截至2020年5月23日,本人暂时还未发现其他的方法

    In [1]: t = ()                                                                                                                                                                    
    
    In [2]: type(t)                                                                                                                                                                   
    Out[2]: tuple
    
    In [3]: del t 
    

    元组元素操作

    元组是不可变的, 所以只有查询方法

    查询

    通过下标查询

    • 超出范围, 会报错IndexError。
    • 同样支持负数取值。
    • 不支持赋值, 元组是不可变的。
    In [5]: t[0]   
    Out[5]: 0
    
    In [6]: t[4]    # 超出范围,报错IndexError
    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    <ipython-input-6-302761d4dd84> in <module>()
    ----> 1 t[4]
    
    IndexError: tuple index out of range
    
    In [7]: t[-1]   # 同样支持负数取值
    Out[7]: 2
    
    In [8]: t[0] = 3   # 不支持赋值, 元组是不可变的
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-8-d7bb3c58ee7f> in <module>()
    ----> 1 t[0] = 3
    
    TypeError: 'tuple' object does not support item assignment
    
    总结:
        1、超出范围, 会报错IndexError。
        2、同样支持负数取值。
        3、不支持赋值, 元组是不可变的。
    

    tuple.index通过值查找索引

    tuple.index方法和list.index方法一致,通过值查找索引
    不存在的抛ValueError

    In [10]: t.index(2)   # 查找2在第几个index
    Out[10]: 2
    
    In [11]: t.index(3)   # 不存在的抛ValueError
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-11-bbaa43d3e6ff> in <module>()
    ----> 1 t.index(3)
    
    ValueError: tuple.index(x): x not in tuple
    
    总结:
        1、不存在的抛ValueError
    

    tuple.count统计值在元组中出现的个数

    tuple.count和list.count方法表现一致

    In [12]: t.count(2)  
    Out[12]: 1
    
    In [13]: t.count(10)    # 统计不存在的值为零
    Out[13]: 0
    
    总结元组特性:
    元组的最大特性是不可变。
    不可变意味着可hash, 意味着可以做字典的key, 可以做set的元素。
    函数时,元组的作用更强大。
    
  • 相关阅读:
    深度优先搜索
    哈希算法
    双指针问题
    基本概念
    Ionic JPush极光推送二
    一条sql获取每个类别最新的一条记录
    Ionic App 更新插件cordova-plugin-app-version
    Ionic跳转到外网地址
    Ionic cordova-plugin-splashscreen
    Web API 上传下载文件
  • 原文地址:https://www.cnblogs.com/cishi/p/12961592.html
Copyright © 2011-2022 走看看