zoukankan      html  css  js  c++  java
  • 三. python元组

    一. 元组

    Python的元组与列表类似,不同之处在于元组的元素不能修改。
    元组使用小括号,列表使用方括号。
    元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

    元组:有序,需要存索引相关信息,不可变

    # 创建空元组
    tup1 = ();
    # 元组中只包含一个元素时,需要在元素后面添加逗号
    tup1 = (50,);

    1.访问元组中的值

    # 元组可以使用下标索引来访问元组中的值
    # 格式:元组名:下标
    tup1 = ('physics', 'chemistry', 1997, 2000); 
    tup2 = (1, 2, 3, 4, 5, 6, 7 );                                     
    print  (tup1[0])  #physics
    print  (tup2[1:5])    #(2, 3, 4, 5)
    print  (tup2[-1])  #7    元组获取最后一个元素-1   倒数是从-1开始
    tup6=(1,2,3,[7,8,9])
    tup6[-1][1]=1000
    print(tup6)              # (1, 2, 3, [7, 1000, 9])

    2.连接组合

    # 元组不能变  是指元组里面的元素不可以改变
    # 元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:
    tup1 = (12, 34.56);
    tup2 = ('abc', 'xyz');
    # 创建一个新的元组
    tup3 = tup1 + tup2;
    print (tup3); #(12, 34.56, 'abc', 'xyz')
    # 元组连接
    t1=(1,2,3)
    t2=(10,25,39)
    t3=t1+t2
    print(t3)   # (1, 2, 3, 10, 25, 39)

    3.del语句来删除整个元组

    # 元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组
    tup6=(1,2,3,[7,8,9])
    del tup6

    4.元组重复

    # 元组重复
    t1=(1,2,3)
    print(t1*3)  #(1, 2, 3, 1, 2, 3, 1, 2, 3)

    5.判断元素是否在元组里

    #判断元素是否在元组里
    t5=(1,2,3,20)
    print(20 in t5)  #True

    6.元组截取

    # 元组截取
    # 格式 :
    #    元组名:[开始下标:结束下标]
    
    #    从开始下标 到结束下标之前
    t9 = ('physics', 'chemistry', 1997, 2000);
    tup8 = (1, 2, 3, 4, 5, 6, 7 );
    print  (tup9[0])  #physics
    print  (tup8[1:5])  #(2, 3, 4, 5)

    7.二维元组 

    # 二维元组 :就是元素为一维元组的的元组
    t0=((1,2,3),(4,5,6),(7,8,9))
    print(t0[1][1])  #5

    8.元组元素个数len()

    # Python 元组 len() 函数计算元组元素个数。
    # tuple2 = (123, 'xyz', 'zara')
    #  aa=len(tuple2)
    #  print(aa)  #3

    9.元组 tuple() 函数将列表转换为元组

     # Python 元组 tuple() 函数将列表转换为元组。
     aList = [123, 'xyz', 'zara', 'abc'];
     aTuple = tuple(aList)
     print  (aTuple)   #(123, 'xyz', 'zara', 'abc')

    10.遍历

     # 元组的遍历
     for x in (1,2,3,4,5,6):
         print(x) #123456

    11.max()

     # Python 元组 max() 函数返回元组中元素最大值。
    ta=(123, 'xyz', 'zara', 'abc')
    print(max(ta))  #zara
  • 相关阅读:
    六、TreeSet中的定制排序
    五、Set接口
    四、List接口
    Vocabulary Recitation 2020/05/20
    Vocabulary Recitation 2020/05/19
    Vocabulary Recitation 2020/05/18
    自控力_第六章
    Vocabulary Recitation 2020/05/17
    Vocabulary Recitation 2020/05/15
    Vocabulary Recitation 2020/05/14
  • 原文地址:https://www.cnblogs.com/Sup-to/p/10840781.html
Copyright © 2011-2022 走看看