1. 元祖
- python的内置数据结构之一,是一个不可变序列
- 不可变序列:没有增删改操作
- 字符串,元祖
- 可变序列:可以增删改,对象地址不发生改变
- 列表,字典
1.1 元祖创建方式
-
使用小括号
- t = (‘python’,‘hello’,90)
-
使用内置函数tuple()
- t = tuple( (‘python’,‘hello’,90))
-
只包含一个元祖的元素需要使用小括号和逗号
- t = (10,)
# 1
t1 = ('python','hello',90)
# 2
t2 = tuple( ('python','hello',90))
# 3
t3 = (10,)
t4 = (10) # 不加逗号会变成int类型
# 空元祖
t5 = ()
t6 = tuple()
1.2 为什么要将元祖设计成不可变序列
- 多任务环境下,同时操作对象时不需要加锁,因此,程序中尽量使用不可变序列
- 注意事项:
- 元祖中存储的是对象的引用
- 如果元祖中对象本身是不可变对象,则不能在引用其他对象
- 如果元祖中的对象是可变对象,则可变对象的引用不允许改变,但数据可以改变
t = (10,[20,30],40)
print(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 不允许修改
#由于[20,30]是列表,可以添加元素
t[1].append(100)
print(t[1],id(t[1]))
'''
(10, [20, 30], 40)
10 - <class 'int'> - 2012026333776
[20, 30] - <class 'list'> - 2012031686592
40 - <class 'int'> - 2012026334736
[20, 30, 100] 2012031686592
'''
1.3 元祖的遍历
- 元祖是可迭代对象,可以使用 for…in 遍历
t = ('python','java',100)
for item in t:
print(item)
'''
python
java
100
'''