Tuple
tuple是一个不可变的有序序列,在某种程度上,元组在索引、嵌套对象和重复方面与列表相似,但元组是不可变的,列表是可变的,tuple一但初始化之后就不能修改。
class tuple([iterable])
tuple接收的参数是一个可迭代对象。
tuple可通过多种方式构建:
tuple_One= ()
tuple_two = "a",
tuple_there = ("a", "b", "c")
tuple_four = tuple(["a", "b", "c"])
temp = (1, 2, 3, 4, 5, 6, 7)
print(id(temp))
tuple_five = tuple(temp)
print(id(tuple_five))
tuple 方法:
- count(self,value):
- value:要统计的值
- 返回值:value 在tuple 出现的次数,没有则返回0
temp = ("peach", "Lemon", "Pear","Lemon", "Pear")
print(temp.count("Lemon"))
print(temp.count("apple"))
- index(self, value, start=None, stop=None):
- value:需要查找index的value
- start:开始位置
- stop:结束位置
- return:返回value第一次出现的index, value不存在则,
Raises ValueError
temp = ("peach", "Lemon", "Pear","Lemon", "Pear")
print(temp.index("Lemon"))
不可变特性
tuple 一但初始化了,元素的值是不可变的:
temp = ("peach", "Lemon", "Pear", "Lemon", "Pear")
temp[0] = "Banana"
执行后Raises一个TypeError
:
TypeError: 'tuple' object does not support item assignment
但是,不可变不是绝对
:
temp = ("peach", "Lemon", ["cranberry", "raspberry","Mango"],"Pear", "Lemon", "Pear")
temp[2][0] = "Banana"
print(temp)
temp[2][0]的值从“cranberry
”变成了“Banana
”。
Why?,不是说不可变的嘛?
因为list序列是可变的,且temp[2][0]的值被改变后,temp[2]的指向没变,所以不建议在tuple存放可变序例元素。
temp_list = ["cranberry", "raspberry", "Mango"]
temp = ("peach", "Lemon",temp_list,"Pear", "Lemon", "Pear")
print(id(temp_list))
temp[2][0] = "Banana"
print(id(temp[2]))
Iterable
tuple 是一个可迭代的,所以可以使用for in 语句
temp = ("peach", "Lemon","Pear", "Lemon", "Pear")
for fruit in temp :
print(fruit)
拆包
tuplu 有一个很重要的特性就是拆包
temp = ("William", 18, "programmer")
name, age, job = temp
print(name,age,job)
name, *other = temp
print(name, other)
def function (name,age,job):
print(name, age, job)
function(*temp)
tuple与list的不同
性能优化
遍历tuple的速度确实比list快。为什么呢?stackoverflow上有人的解释:
总体可分以下几点:
tuple中是不可变的,在CPython中tuple被存储在一块固定连续的内存中,创建tuple的时候只需要一次性分配内存。但是List被的被存储在两块内存中,一块内存固定大小,记录着Python Object(某个list对象)的信息,另一块是不固定大小的内存,用来存储数据。所以,查找时tuple可以快速定位(C中的数组);list必须遍历(C中的链表)。在编译中,由于Tuple是不可变的,python编译器将它存储在它所在的函数或者模块的“常量表”(constants table)中。运行时,只要找到这些预构建的常量元组。但是List是可变的,必须在运行中构建,分配内存。
当Tuple的元素是List的时候,它只存储list的引用,(C中定长数组里一个元素是指向某个链表的指针),定位查找时它还是会比List快。
CPython中已经做了相关优化以减少内存分配次数:释放一个List对象的时候,它的内存会被保存在一个自由List中以重复使用。不过非空list的创建时,仍然需要给它分配内存存储数据。
可做dict的key
- dict的key必须是一个可hash的对象:而list没有实现
__hash__()
这个魔术方法。
temp_list = []
temp_tuple = tuple()
temp_dict = {}
temp_dict[temp_tuple] = "tuple"
print(temp_dict)
temp_dict[temp_list] = "list"
如果你觉得还不错,那就点个赞吧
听说喜欢留言、分享的人
运气都不会差

python笔记侠