1.创建元组
>>> tuple = (1,2,3,4,5) >>> tuple (1, 2, 3, 4, 5)
2.访问元组
>>> tuple = (1,2,3,4,5) >>> tuple (1, 2, 3, 4, 5) >>> tuple[1:3] (2, 3)
3.注意:如果创建的元祖只有一个元素,请在元素后面加上逗号
>>> tup = () >>> tup1 = (1) >>> tup2 = (1,) >>> type(tup) <class 'tuple'> >>> type(tup1) <class 'int'> >>> type(tup2) <class 'tuple'>
4.元组修改
4.1:元组内元素不可修改
>>> tup = (1,'zc','cc','2','gg') >>> tup[1] = 2 Traceback (most recent call last): File "<pyshell#103>", line 1, in <module> tup[1] = 2 TypeError: 'tuple' object does not support item assignment
4.2:只可删除整个元组
>>> tup = (1,'zc','cc','2','gg') >>> del tup[1] Traceback (most recent call last): File "<pyshell#105>", line 1, in <module> del tup[1] TypeError: 'tuple' object doesn't support item deletion >>> del tup >>> tup Traceback (most recent call last): File "<pyshell#107>", line 1, in <module> tup NameError: name 'tup' is not defined
4.3:修改元组内部,须切片拷贝
>>> temp = ('小鸡','小猪','小鸭','小狗') >>> temp[:2] + ('通过切片增加一个元素',) + temp[2:] ('小鸡', '小猪', '通过切片增加一个元素', '小鸭', '小狗')
>>> temp = ('小鸡','小猪','小鸭','小狗') >>> temp[:1] + temp[2:] ('小鸡', '小鸭', '小狗')
4.4:用del删除整个元组
>>> temp = ('小鸡','小猪','小鸭','小狗') >>> del temp >>> temp Traceback (most recent call last): File "<pyshell#123>", line 1, in <module> temp NameError: name 'temp' is not defined
5.元组的方法
5.1:count 统计元素在列表中出现的次数
>>> temp = ('小鸡','小猪','小鸭','小狗','小狗') >>> temp.count('小狗') 2 >>> temp.count('小鸡') 1
5.2:index() 查到元素在列表中的位置
>>> temp = ('小鸡','小猪','小鸭','小狗','小狗') >>> temp.index('小猪') 1