Python基础(元祖,集合)
一,什么是元祖
- 元祖
- Python内置的数据结构之一,是一个不可变序列
不可变序列与可变序列
-
不可变序列:字符串、元祖
- 不可变序列特点:没有增、删、改的操作
-
可变序列:列表、字典
- 可变序列:可以对序列执行增、删、改操作,对象地址不发生更改
-
''' 可变序列,列表、字典 ''' lst=[10,20,30] print(id(lst)) lst.append(300) print(id(lst))
输出:
2332067655040
2332067655040
不可变序列,更改好id会变
'''
不可变序列
'''
s='hello'
print(id(s))
s=s+' world'
print(s)
print(id(s))
输出:
2528903130032
hello world
2528903142640
元祖示例
t = (‘Python’,‘hello’,90)
与列表的区别,列表是方括号 [] , 元祖是小括号 ()
二、元祖的创建方式
-
元祖的创建方式
-
直接小括号
-
''' 元祖的创建方式 ''' ''' 第一种,使用() ''' t= ('Python','hello','world',98) print(t) print(type(t))
-
-
使用内置函数:tuple()
''' 第二种:使用内置函数tuple() ''' t1=tuple(('hello0','world')) print(t1) print(type(t1))
-
元祖中只有一个元素的情况
-
只有一个元祖的情况,逗号不能省略
-
'''只包含一个元祖的元素需要使用逗号和小括号''' t=(10,) print(t) print(type(t)) t3=('hello',) print(t3) print(type(t3))
-
输出:
(10,) <class 'tuple'> ('hello',) <class 'tuple'>
-
-
-
空元祖的创建方式
t5=()
t6=tuple() -
'''空元祖的创建方式''' '''回顾空列表的创建方式''' lst=[] lst1 = list() '''空字典的创建方式''' d={ } d2 = dict() #空元祖 t5=() t6=tuple() print(t5) print(t6)
输出:
() ()
三、为什么要将元祖设计成不可变序列
-
在多任务环境下,同时操作对象时不需加锁
-
因此,在程序中尽量使用不可变序列
-
注意事项:元祖中存储的是对象的引用
- 如果元祖中对象本身不可变对象,则不能再引用其他对象
- 如果元祖中的对象是可变对象,则可变对象的引用不允许改变,但数据可以改变
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(