Python学习(五):基本的数据结构——元组及常用方法
1.元组的概述:
元组与列表类似,由任意类型的元素组成序列;
元组是不可变的(与列表不同处);
2.元组的创建及检验:
>>> tuple_1 = (1,2,3,4) >>> tuple_1 (1, 2, 3, 4) >>> tuple_2 = 1,2,3 >>> tuple_2 (1, 2, 3) >>> tuple_3 = (1) >>> type(tuple_3) <class 'int'> >>> tuple_3 = (1,) #注意,创建单个值的元组时候,必须后面加, >>> type(tuple_3) <class 'tuple'> >>> tuple_3 = 1, >>> type(tuple_3) <class 'tuple'> >>> tuple_3 (1,)
>>> tuple_4=() #创建空元组直接括号即可。
>>> type(tuple_3)
<class 'tuple'>
2.元组的切片等方法:
>>> tuple_2 = 22, 44, 66 >>> tuple_2 (22, 44, 66) >>> tuple_2[2] 66 #注意,元组是不可变,如下更改元组元素,会报错 >>> tuple_2[2]=88 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment #重新赋值的方法,取变量赋值 >>> a, b, c=tuple_2 >>> a 22 >>> a, b = b, a >>> a 44 #数组转为元组 >>> lis = ['q','w','e'] >>> tuple(lis) ('q', 'w', 'e') #字典转为元组,注意,转换中会将key转为元组元素 >>> dic={'a':1,'b':2} >>> tuple(dic) ('a', 'b')