学习内容:元祖类型内置方法

元组类型内置方法

tuple(掌握)

元组是不可变的列表,即元组的值不可更改,因此元组一般只用于只存不取的需求。也因此元组可以被列表取代掉,所以元组相比较列表使用的很少。元组相比较列表的优点为:列表的值修改后,列表的结构将会发生改变,而元组只需要存储,因此列表在某种程度上而言需要占用更多的内存。但是目前工业上内存已经不是问题了,所以工业上元组一般不会使用。

  1. 用途:多个装备、多个爱好、多门课程,甚至是多个女朋友

  2. 定义:在()内可以有多个任意类型的值,逗号分隔元素

    my_play_game = ('lol', 'cf', 'qq')
    print(f"my_play_game: {my_play_game}")
    
    
    
    my_play_game: ('lol', 'cf', 'qq')
    name_str = ('egon')  # ()只是普通包含的意思
    name_tuple = ('egon',)
    
    print(f"type(name_str): {type(name_str)}")
    print(f"type(name_tuple): {type(name_tuple)}")
    
    
    
    type(name_str): <class 'tuple'>
    type(name_tuple): <class 'tuple'>
  3. 常用操作+内置方法:常用操作和内置方法:

优先掌握

  1. 索引取值

    name_tuple = ('lol','dnf','cf','qq')
    print(f'name_list:{name_list[0]}')
    
    
    name_tuple:lol
  2. 切片(顾头不顾尾,步长)

    name_tuple = ('lol','dnf','cf','qq')
    print(f"name_list[1:3:2]:{name_list[1:3:2]}")
    
    
    name_tuple[1:3]:('dnf',)
  3. 长度len

    name_tuple = ('lol','dnf','cf','qq')
    print(f'len(name_tuple):{len(name_tuple)}')
    
    
    len(name_tuple):4
  4. 成员运算in和not in

    name_tuple = ('lol','dnf','cf','qq')
    print(f"dnf in name_tuple:{'dnf' in name_tuple}")
    print(f"dnf not in name_tuple:{'dnf'not in name_tuple}")
    
    
    dnf in name_tuple:True
    dnf not in name_tuple:False
  5. 循环

    name_tuple = ('lol','dnf','cf','qq')
    for i in name_tuple :
        print(f'name_tple:{i}')
    
    
    
    name_tple:lol
    name_tple:dnf
    name_tple:cf
    name_tple:qq   
  6. count 获取指定元素的值

    name_tuple = ('lol','dnf','cf','qq')
    print(f"name_tuple.count('cf'):{name_tuple.count('cf')}")
    
    
    name_tuple.count('cf'):1
  7. index 获取指定元素的索引值

    name_tuple = ('lol','dnf','cf','qq')
    print(f"name_tuple.index('qq'):{name_tuple.index('qq')}")
    
    
    
    name_tuple.index('qq'):3
  8. 存一个值or多个值:一个值

  9. 有序or无序:有序

    name_tuple = ('jin',)
    print(f'id(name_tuple):{id(name_tuple)}')
    
    
    id(name_tuple):30399008
  10. 可变or不可变:不可变数据类型

    n = ['a','b','c']
    print(f'id(n[0]):{id(n[0])}')
    n[0] = 'd'
    print(f'id(n[0]):{id(n[0])}')
    
    
    id(n[0]):31019392
    id(n[0]):30591272

    列表可变的原因是:索引所对应的值的内存地址是可以改变的

    元组不可变得原因是:索引所对应的值的内存地址是不可以改变的,或者反过来说,只要索引对应值的内存地址没有改变,那么元组是始终没有改变的。

    n1 = ('a','b','c',['d','e','f'])
    print(f'id(n1[0]):{id(n1[0])}')
    print(f'id(n1[0]):{id(n1[1])}')
    print(f'id(n1[0]):{id(n1[2])}')
    print(f'id(n1[0]):{id(n1[3])}')
    
    n1[3][0] = 'D'
    print(f'n1[3][0]:{n1[3][0]}')
    print(f'id(n1[3]:{id(n1[3])}')
    print(f'n1:{n1}')
    
    
    
    id(n1[0]):6574464
    id(n1[0]):6556336
    id(n1[0]):6144888
    id(n1[0]):31868872
    n1[3][0]:D
    id(n1[3]:31868872
    n1:('a', 'b', 'c', ['D', 'e', 'f'])

猜你喜欢

转载自www.cnblogs.com/jincoco/p/10923616.html
0条评论
添加一条新回复