元组
元组合列表非常相似
最大的不同是元组是不可改变的,不能随意进行插入删除操作
列表用[]而元组用()
注意元组的最有特征的符号是逗号(,)
>>> tuple1=(1,2,3,4,5,6,7,8)
访问元组元素
>>> tuple1[1]
2
分片
>>> tuple1[5:]
(6, 7, 8)
>>> tuple1[:5]
(1, 2, 3, 4, 5)
>>> tuple2 = tuple1[:]
>>> tuple2
(1, 2, 3, 4, 5, 6, 7, 8)
创建单个元素的元组
>>> temp = (1)
>>> temp
1
>>> type(temp)
<class 'int'>
此时为Int类型而不是tuple类型
>>> temp = (1,)
>>> temp
(1,)
>>> type(temp)
<class 'tuple'>
此时才为tuple类型
>>> temp2 = 2,3,4
>>> type(temp2)
<class 'tuple'>
可以不用括号,最关键的是要有逗号
回忆List类型
创建空列表
>>> list1=[]
>>> type(list1)
<class 'list'>
例子:
>>> 8*(8)
64
>>> 8*(8,)
(8, 8, 8, 8, 8, 8, 8, 8)
“更新”和删除一个元组
例如字符串可以切片然后修改
元组也是如此
并不是真正意义上的修改,而是替换
>>> temp =('andy','amy','cdy','lyf')
4
>>> temp
('andy', 'amy', 'cdy', 'lyf')
>>> temp =temp[:2]+('aaa',)+temp[:2]
>>> temp
('andy', 'amy', 'aaa', 'andy', 'amy')
备注:temp标签先指向原来的元组,然后通过分片产生一个新的元组后再次赋值给temp标签,所以原来的元组内存想会被操作系统回收。
如果一块内存没有标签指向它,它将会被操作系统回收;如果有多个标签指向同一块内存,每次delete一下标签则会删除此标签,直到指向此内存空间的标签数为0,操作系统则会回收此内存。
小结:哪些操作符可以用在元组上:
1.拼接操作符 + (操作符两边要都是同一类型(元组类型))
2.重复操作符(*)
3.成员操作符(in / not in)
4.逻辑操作符(and or ...)