python学习7-元组

一、元组的定义 用()定义

python内置的数据结构之一,是一个不可变序列

二、不可变序列和可变序列

1、不可变序列:(字符串、元组) 没有增、删、改的操作,地址发生变化
2、可变序列:(列表、字典) 可以执行增、删、改操作,对象地址不发生更改

三、元组的创建方式

1、直接小括号()

t=('python','world',88)  #('python', 'world', 88)
print(type(t)) #<class 'tuple'>
#可以省略小括号
t2='python','world',88
print(type(t2)) #<class 'tuple'>

2、使用内置函数tuple()

t1=tuple(('python','world',88))  #('python', 'world', 88)
print(type(t1)) #<class 'tuple'>

3、只包含一个元素的元组需要使用逗号和小括号

t3=('python') #<class 'str'>
t3=('python',)  #<class 'tuple'>

4、空元组

t4=()   #()
t4=tuple() #()

四、为什么将元组设计成不可变序列?

  • 1、在多任务环境下,同时操作对象时不需要加锁;
  • 2、在程序中尽量使用不可变序列;
  • 3、注意事项:元组中存储的是对象的引用

如果元组中对象本身是不可变对象,则不能再引用其他对象;
如果元组中的对象是可变对象,则可变对象的引用不允许改变,但数据可以改变

t=(10,[20,30],40)
print(t)   #(10, [20, 30], 40)
print(type(t))  #<class 'tuple'>
print(t[0],type(t[0]))  #10 <class 'int'>
print(t[1],type(t[1]))  #[20, 30] <class 'list'>
print(t[2],type(t[2]))  #40 <class 'int'>

print(id(100))   #140705845990144
t[1]=100  #TypeError: 'tuple' object does not support item assignment  元组是不允许修改元素的
#由于[20,30]列表,而列表是可变序列,所以可以向列表中添加元素,而列表的内存地址不变
t[1].append(100)
print(t)  #(10, [20, 30, 100], 40)

五、元组的遍历

t=('python','world',98)

1、使用索引

print(t[2])  #98
print(t[3])  #IndexError: tuple index out of range

2、元组是可迭代对象,所以可以使用for…in进行遍历

for item in t:
    print(item)  #python   world   98

猜你喜欢

转载自blog.csdn.net/qq_43757976/article/details/130350045