python 元组
知识点
-
元组也是python内置的数据结构之一,是一个不可变序列
-
可变序列就是可以进行增删改查的操作,且id标识不变
-
为什么要将元组设计成不可变序列:
答:1.在多任务环境下,同时操作对象时不需要加锁
2.在程序中尽量使用不可变序列(只能看不能改)
元组的创建方式
# 教育机构 舒寒科技有限公司
# 学习者 舒寒拽少
# 学习时间: 2022/1/10 15:42
'''元组的创建方式'''
# 第一种创建方式,使用()
t=('python','world',98)
print(t)
print(type(t))
t2='python','world',98 #省略了小括号
print(t2)
print(type(t2))
t3=('python',) #当元组只有一个元素时,要在后面加上逗号,不然会认为是string类型
print(t3)
print(type(t3))
# 第二种创建方式,使用内置函数tuple()
t1=tuple(('python','world',98))
print(t1)
print(type(t1))
#空列表
lst=[]
lst1=list()
#空字典
d={ }
d1=dict()
#空元组
t4=()
t5=tuple()
print('空列表',lst,lst1)
print('空字典',d,d1)
print('空元组',t4,t5)
运行结果:
('python', 'world', 98)
<class 'tuple'>
('python', 'world', 98)
<class 'tuple'>
('python',)
<class 'tuple'>
('python', 'world', 98)
<class 'tuple'>
空列表 [] []
空字典 {} {}
空元组 () ()
元组的不可变性
元组是不可变序列,所以元组里面的元素是不能改变的,但如果元组里面有像列表,字典这些可变序列的话,可以在列表或字典里面添加数据,因为他们是可变序列,增删改查后的id内存地址是不会改变的。
# 教育机构 舒寒科技有限公司
# 学习者 舒寒拽少
# 学习时间: 2022/1/11 10:09
t=(10,[20,30],9) #元组里面的元素为列表
print(t)
print(type(t))
#将元组以列表的形式输出。
print(t[0],type(t[0]),id(t[0]))
print(t[1],type(t[1]),id(t[1]))
print(t[2],type(t[2]),id(t[2]))
#尝试将t[1]修改为100
print(id(100))
# t[1]=100 不能修改元组里面的元素
t[1].append(100) #因为元组里面的元素有列表,而列表是可变序列,所有可以添加元素在里面,添加完id不变
print(t,id(t[1]))
运行结果:
(10, [20, 30], 9)
<class 'tuple'>
10 <class 'int'> 1611261739536
[20, 30] <class 'list'> 1611263093760
9 <class 'int'> 1611261739504
1611261742416
(10, [20, 30, 100], 9) 1611263093760
元组的遍历
# 教育机构 舒寒科技有限公司
# 学习者 舒寒拽少
# 学习时间: 2022/1/11 10:34
#元组的遍历
t=('python','world',98)
'''第一种获取元组元素的方式,使用索引'''
print(t[0])
print(t[1])
print(t[2])
# print(t[3]) 超出范围
'''第二种方式,遍历元组'''
for item in t:
print(item)
运行结果:
python
world
98
python
world
98