Python基础之元组概述及基本操作
元组的概述
-
Python内置函数的数据结构之一,是一个不可变序列
-
不可变序列与可变序列
1. 不可变序列: 字符串,元组 不可变序列: 没有增删改的操作 2. 可变序列: 列表,字典 可变序列: 可以对序列执行增删改操作,对象地址不发生更改
实例演示
- 可变序列 列表 字典
- 可以对序列执行增删改操作,对象地址不发生更改
lst=[10,20,30]
print('原列表元素和ID: ',lst,id(lst))
lst.append(40)
print('修改过后的列表: ',lst,id(lst))
执行结果:
原列表元素和ID: [10, 20, 30] 2177764708936
修改过后的列表: [10, 20, 30, 40] 2177764708936
- 不可变序列 字符串 元组
s='hello'
print('原字符串和ID: ',s,id(s))
s=s+'world'
print('修改后字符串和ID: ',s,id(s))
执行结果:
原字符串和ID: hello 2177765251376
修改后字符串和ID: helloworld 2177770258352
元组的创建
- 元组的创建方式
1. 直接小括号:
t=('python','hello',10)
2. 使用内置函数tuple()
t=tuple(('python','hello',20))
3. 只包含一个元组的元素需要使用逗号和小括号
t=(10,)
- 使用小括号创建元组
t=('python','hello',10)
print(t,type(t))
执行结果:
('python', 'hello', 10) <class 'tuple'>
- 创建元组可以省略小括号
t2='python','hello',10
print(t2,type(t2))
执行结果:
('python', 'hello', 10) <class 'tuple'>
- 只包含一个元组的元素需要使用逗号和小括号
t3=('python',)
print(t3,type(t3))
执行结果:
('python',) <class 'tuple'>
- 使用函数tuple()创建元组
t=tuple(('python','hello',20))
print(t,type(t))
执行结果:
('python', 'hello', 20) <class 'tuple'>
- 创建空元组
t=()
print(t,type(t))
执行结果:
() <class 'tuple'>
为什么元组是一个不可变序列
- 在多任务环境下,同时操作对象时不需要加锁
- 因此,在程序中尽量使用不可变序列
- 元组中存储的是对象的引用
- 如果元组中对象本身不可变对象,则不能在引用其他对象
- 如果元组中对象是可变对象,则可变对象的引用不允许改变,但数据可以改变
实例演示
- 获取单个元组中对象的类型 及 ID
t=(10,20,[30,40,50],1,2)
print(t,type(t))
print('----------在元组中的列表添加元素100---------------')
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]))
print(t[3],type(t[3]),id(t[3]))
print(t[4],type(t[4]),id(t[4]))
执行结果:
(10, 20, [30, 40, 50], 1, 2) <class 'tuple'>
----------获取单个元组中对象的类型 及 ID---------------
10 <class 'int'> 140734345867824
20 <class 'int'> 140734345868144
[30, 40, 50] <class 'list'> 2180709045320
1 <class 'int'> 140734345867536
2 <class 'int'> 140734345867568
- 在元组中的列表添加元素100
print('添加之前的元素及列表ID: ',t,id(t[2]))
t[2].append(100)
print('添加之后的元素及列表ID: ',t,id(t[2]))
执行结果:
添加之前的元素及列表ID: (10, 20, [30, 40, 50], 1, 2) 2180709045320
添加之后的元素及列表ID: (10, 20, [30, 40, 50, 100], 1, 2) 2180709045320
元组的遍历
元组是可迭代对象, 所以可以使用for i in 进行遍历
语法格式:
for i in 元组名
print(元组名)
实例演示
t=['python','hello',10]
for i in t:
print(i)
执行结果:
python
hello
10