zoukankan      html  css  js  c++  java
  • 8.Python元组

     

    元组

     
    Python 的元组与列表类似,不同之处在于元组的元素不能修改。
    元组使用小括号,列表使用方括号。元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
    In [1]:
    t1  = ()
    
    print(type(t1))
    
     
    <class 'tuple'>
    
    In [2]:
    t2 = ('hello',) #定义一个元素的元组时必须要加逗号,不然被认为是字符串类型
    t3 = ('hello')
    
    print(type(t2))
    print(type(t3))
    
     
    <class 'tuple'>
    <class 'str'>
    
    In [3]:
    tup = (1,2,3,4,5,6,8,9,7,10)
    print(max(tup))
    print(min(tup))
    print(len(tup))
    print(sum(tup))
    print(tup.count(6))   #找出元组中6的个数
    print(tup.index(6))   #找出元组中找出6的下标位置
    
     
    10
    1
    10
    55
    1
    5
    
     

    装包与拆包

    In [4]:
    t1 = (1, 2, 3)
    
    In [5]:
    #变量个数与元组个数不一致时会报错
    #a,b = t1            #ValueError: too many values to unpack (expected 2)
    #a, b, c, d = t1      #ValueError: not enough values to unpack (expected 4, got 3)
    a, b, c = t1
    
     

    *a :一颗星表示接收未知的个数

    过程: step1拆包:底层先把元组(列表)拆包为1,2,3,4,5,6; step2装包:然后将1给a,将6给b;检测到带有*,则将剩余的都给

    In [6]:
    t1 = (1, 2, 3, 4, 5, 6)
    a, *_, b = t1
    
    print(a)
    print(b)
    print(_)
    
     
    1
    6
    [2, 3, 4, 5]
    
    In [7]:
    t1 = (1, 2)
    a, *b, c = t1
    print(a)
    print(b)
    print(c)
    
     
    1
    []
    2
    
  • 相关阅读:
    performance benchmark : memcached vs Kyoto Tycoon
    Adhesive框架系列文章应用程序信息中心模块实现
    神奇的Redis
    使用代码测试ASP.NET MVC2执行流程
    linq2sql代码大全
    7/17博客园活动浅谈网站架构中缓存的应用所有资料
    浅谈.NET下的多线程和并行计算(十四)并行计算前言
    公司.NET 3.5培训资料分享
    mongodb分片集群(sharding with replica set)配置
    mongodb有关的研究
  • 原文地址:https://www.cnblogs.com/King-Penguin/p/12156598.html
Copyright © 2011-2022 走看看