-
元组属性
1.任意对象的有序集合
2.通过偏移存取
3.属于不可变序列类型
4.固定长度,异构,任意嵌套
5.对象引用的数组 -
元组常用方法
1.单个元素的元组
T = (0,) #注意逗号的使用
L = (0)
print('T is {}, type is {}'.format(T,type(T)))
print('L is {}, type is {}'.format(L,type(L)))
运行结果:
T is (0,), type is <class 'tuple'>
L is 0, type is <class 'int'>
2.4个元素的元组
T = (0,'bb',3,3.4)
L = 0,'bb',3,3.4 #这里没有使用括号,另一种定义元组的方式
print('T is {}, type is {}'.format(T,type(T)))
print('L is {}, type is {}'.format(L,type(L)))
运行结果:
T is (0, 'bb', 3, 3.4), type is <class 'tuple'>
L is (0, 'bb', 3, 3.4), type is <class 'tuple'>
3.元组嵌套
T = ('abc',('b','cd'))
print('T is {}, type is {}'.format(T,type(T)))
print('T[1] is {}, type is {}'.format(T[1],type(T[1])))
运行结果:
T is ('abc', ('b', 'cd')), type is <class 'tuple'>
T[1] is ('b', 'cd'), type is <class 'tuple'>
4.可迭代对象的元素构成的元组
T = tuple('hello')
print('T is {}, type is {}'.format(T,type(T)))
运行结果:
T is ('h', 'e', 'l', 'l', 'o'), type is <class 'tuple'>
5.索引,分片,长度,索引的索引
T = tuple('hello')
val = T[0]
print('索引为0时,元组的元素是'+val)
val2 = T[1:3] #分片
print('索引为1~2时,元组的元素是{}'.format(val2))
length = len(T)
print('T元组有元素{}个'.format(length))
L = (1,(2,3),4,(5,6))
val = L[1][1]
print('索引的索引,{}'.format(val))
运行结果:
索引为0时,元组的元素是h
索引为1~2时,元组的元素是('e', 'l')
T元组有元素5个
索引的索引,3
6.合并,重复
T = tuple('hello')
L = (1,(2,3),4,(5,6))
N1 = T + L
N2 = T * 2
print('元组合并操作得到N1元组{}'.format(N1))
print('元组重复操作得到N2元组{}'.format(N2))
运行结果:
元组合并操作得到N1元组('h', 'e', 'l', 'l', 'o', 1, (2, 3), 4, (5, 6))
元组重复操作得到N2元组('h', 'e', 'l', 'l', 'o', 'h', 'e', 'l', 'l', 'o')
7.成员关系判断
T = tuple('hello')
if 'o' in T:
print('o 在 N2元组里{}'.format(T))
if 'lo' not in T:
print('lo 不在 N2元组里{}'.format(T))
运行结果:
o 在 N2元组里('h', 'e', 'l', 'l', 'o')
lo 不在 N2元组里('h', 'e', 'l', 'l', 'o')
8.迭代
T = tuple('hello')
for x in T:
print('打印元素元素:{}'.format(x))
运行结果:
打印元素元素:h
打印元素元素:e
打印元素元素:l
打印元素元素:l
打印元素元素:o
9.搜索、计数
T = tuple('hello')
index = T.index('e') #返回第一次出现的索引
count = T.count('l')
print('T元组中e元素的索引{},l元素个数{}'.format(index, count))
运行结果:
T元组中e元素的索引1,l元素个数2