26 元组类型内置方法

目录

tuple(掌握)

'''
# 优先掌握
   1.按索引取值
   2.切片
   3.长度
   4.成员运算 in 和 not in
   5.循环
'''

 

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

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

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

# my_girl_friend = tuple(('jason','tank','sean'))
my_girl_friend = ('jason', 'tank', 'sean')

print(f"my_girl_friend: {my_girl_friend}")
my_girl_friend: ('jason', 'tank', 'sean')
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 'str'>
type(name_tuple): <class 'tuple'>

3.常用操作+内置方法:常用操作和内置方法:

元组类型内置方法-简单.jpg

1.索引取值

# tuple之索引取值
name_tuple = ('tank', 'jason', 'tank', 'sean')
# name_tuple[0] = 'tank handsom'  # 报错

print(f"name_tuple[0]: {name_tuple[0]}")
name_tuple[0]: tank

2.切片(顾头不顾尾,步长)

# tuple之切片
name_tuple = ('tank', 'jason', 'tank', 'sean')

print(f"name_tuple[1:3:2]: {name_tuple[1:3:2]}")
name_tuple[1:3:2]: ('jason',)

3.长度

# tuple之长度
name_tuple = ('tank', 'jason', 'tank', 'sean')

print(f"name_tuple: {name_tuple}")
name_tuple: ('tank', 'jason', 'tank', 'sean')

4.成员运算

# tuple之成员运算
name_tuple = ('tank', 'jason', 'tank', 'sean')

print(f"'tank' in name_tuple: {'tank' in name_tuple}")
'tank' in name_tuple: True

5.循环

# tuple之循环
name_tuple = ('tank', 'jason', 'tank', 'sean')

for name in name_tuple:
    print(name)
tank
jason
tank
sean

6.count()

# tuple之count()
name_tuple = ('tank', 'jason', 'tank', 'sean')

print(f"name_tuple.count('tank'): {name_tuple.count('tank')}")
name_tuple.count('tank'): 1

7.index()

# tuple之index()
name_tuple = ('tank', 'jason', 'tank', 'sean')

print(f"name_tuple.index('tank'): {name_tuple.index('tank')}")
name_tuple.index('tank'): 0

4.存一个值or多个值:一个值

5.有序or无序:有序

name_tuple = ('tank',)
print(f'first:{id(name_tuple)}')
first:4394454152

6.可变or不可变:不可变数据类型

元组和列表(了解)

l = ['a', 'b', 'c']
print(f"id(l[0]): {id(l[0])}")
l[0] = 'A'
print(f"id(l[0]): {id(l[0])}")
id(l[0]): 4357367208
id(l[0]): 4357775176

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

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

t1 = (['a', 'b', 'c'], 'wc', 'office')

print(f"id(t1[0]): {id(t1[0])}")
print(f"id(t1[1]): {id(t1[1])}")
print(f"id(t1[2]): {id(t1[2])}")

t1[0][0] = 'A'
print(f"t1[0][0]: {t1[0][0]}")
print(f"id(t1[0]): {id(t1[0])}")
print(f"t1: {t1}")
id(t1[0]): 4394709960
id(t1[1]): 4374626968
id(t1[2]): 4394453568
t1[0][0]: A
id(t1[0]): 4394709960
t1: (['A', 'b', 'c'], 'wc', 'office')

元组类型内置方法-咋整的.jpg

掌握—》熟悉—》了解
- 掌握:倒背如流。
- 熟悉:正背如流。
- 了解:看到能够想起。


posted @ 2019-05-05 00:15  tank_jam  阅读(140)  评论(0编辑  收藏  举报