元组

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

不可变序列与可变序列

不变可变序字符串、元组
不变可变序列:没有增、删,改的操作

可变序列[[8. 列表]]、[[9. 字典]]

可变序列:可以对序列执行增、删、改操作,对象地址不发生改变

元组创建方式

  • 直接小括号
    t=(‘Python hello’, 90)
  • 使用内置函数tuple()
    t= tuple((‘python’, ‘hello’, 90))
  • 只包含一个元组的元素需要使用逗号和小括号
    t=(10,)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
t=('Python hello', 90)
print(t)
t1= tuple(('python', 'hello', 90))
print(t1)
t2 = 'hello','world'
print(t2,type(t2))

## 空元组
t3 =()
t4 = tuple()
# 空列表
lst= []
lst = list()
# 空字典
d = {}
d1= dict()

('Python hello', 90)
('python', 'hello', 90)
('hello', 'world') <class 'tuple'>

为什么要将元组设计成不可变序列

为什么要将元组设计成不可变序列
  • 在多任务环境下,同时操作对象时不需要加锁
  • 因此,在程序中尽量使用不可变序列
  • 注意事项:元组中存储的是对象的引用
    1. 如果元组中对象本身不可对象,则不能再引用其它对象
    2. 如果元组中的对象是可变对象,则可变对象的引用不允许改变,但数据可以改变
1
2
3
4
5
6
7
8
9
10
t = (1,[1,10,100],20)
print(t,type(t))
print(t[0],type(t))
print(t[1],type(t))
print(t[2],type(t))

# 修改t[1]
# t[1] = 100 # tuple' object does not support item assignment
t[1].append(100)
print(t)
(1, [1, 10, 100], 20) <class 'tuple'>
1 <class 'tuple'>
[1, 10, 100] <class 'tuple'>
20 <class 'tuple'>
(1, [1, 10, 100, 100], 20)

元组遍历

1
2
3
t = (1,[1,10,100],20)
for x in t:
print(x)
1
[1, 10, 100]
20