zoukankan      html  css  js  c++  java
  • 学习python -- 第009天 元组

    元组

    元组

     1 #
     2 # @author:浊浪
     3 # @version:0.1
     4 # @time: 2021/3/14 9:22
     5 # 元组
     6 '''可变序列和不可变序列'''
     7 
     8 # 可变序列 列表, 字典
     9 lst = [100, 522, 45]
    10 print(id(lst))  # 54997672
    11 lst.append(14)
    12 print(id(lst))  # 54997672
    13 
    14 # 不可变序列: 字符串, 元组, 修改后产生了新的对象,故地址改变
    15 s = 'hello'
    16 print(id(s))  # 60004064
    17 s = s + 'ssss'
    18 print(id(s))  # 58551896

    元组的创建

     1 #
     2 # @author:浊浪
     3 # @version:0.1
     4 # @time: 2021/3/14 9:43
     5 # 元组的创建
     6 # 第一种 使用()
     7 t = ('python', 40, "jjjj")
     8 print(type(t))
     9 
    10 t1 = ('python',)  #若元组里只有一个元素,则必须后面加个逗号,否则会判定为字符串
    11 t2 = ('python')
    12 print(t1)
    13 print(t2)
    14 print('t1的类型:', type(t1),'t2的类型:', type(t2))
    15 
    16 # 第二种 使用内置函数tuple()
    17 t3 = tuple(('sssds', 88, 98))
    18 print(t3,type(t3))
    19 
    20 # 空元组
    21 t4 = ()  # 无需逗号
    22 t5 = tuple()
    23 # 空列表
    24 lst = []
    25 lst1 = list()
    26 # 空字典
    27 dct = {}
    28 dct1 = dict()
    29 
    30 print('空元组:', t4, t5)
    31 print('空列表:', lst, lst1)
    32 print('空字典:', dct, dct1)

    元组的特点及其遍历

    通俗来说就是,

    当元组里有不可变对象时,这个不可变对象不可以被修改,如元组t[1]是'hello',则本可以进行这个操作:t[1] = 'aaa' 这个操作时不被允许的,会报错: TypeError: 'tuple' object does not support item assignment

    当元组里有可变对象时,这个可变对象也是不能被修改的,但是这个可变对象里面的数据可以修改。 如 t[2]是[10, 20] ,可以执行t[2].append(100) 的操作,但不可以执行t[2] = [10, 20, 30]的操作 同样的错误:TypeError: 'tuple' object does not support item assignment

     1 #
     2 # @author:浊浪
     3 # @version:0.1
     4 # @time: 2021/3/14 10:02
     5 # 
     6 t = ('python', 10, [10, 20], "jjjj")
     7 # 以下是修改元组的元素会报错
     8 # t[0] = 'ssds' # 报错TypeError: 'tuple' object does not support item assignment
     9 # t[1] = 100   # 报错TypeError: 'tuple' object does not support item assignment
    10 
    11 # t[2] = [10 , 20, 30]  # TypeError: 'tuple' object does not support item assignment
    12 t[2].append(100)
    13 print(t)
    14 
    15 
    16 # 元组的遍历
    17 for i in t:
    18     print(i)
    认清现实,放弃幻想。 细节决定成败,心态放好,认真学习与工作。
  • 相关阅读:
    IDEA 远程调试springboot
    Mybatitas-plus实现逻辑删除
    java通过poi导出excel
    js 展示当前时间
    Linux环境下服务自启
    Spring自带定时器@Scheduled
    Quartz任务调度框架相关方法、参数理解
    Quartz 实现定时任务
    mysql 使用union(all) + order by 导致排序失效
    mongodb的查询操作
  • 原文地址:https://www.cnblogs.com/jyf2018/p/14531621.html
Copyright © 2011-2022 走看看