文章目录
1.元组的定义
(1)元组:带了紧箍咒的列表,也可以存储任意数据类型
(2)元组特性:
-
没有增删改操作,不可变数据类型;虽然不能直接的对元组进行更改,但是如果元组中包含可变数据类型元素,可以根据元组中包含的元素,间接的对元组进行修改
-
在定义元组时,如果元组中只有一个元素必须在元素后面加",",否则该元组类型非元组,而是该元素的类
(3)定义一个空元组:tu=()
(4)类型:tuple
2.元组的常用方法
2.1元组中元素的查找
(1)count 计数
>>> tt
(1, 2, 5, 'python', [1, 2, 'hello', 'python'], 'python')
>>> tt.count('python')
2
>>> tt.count(1)
1
>>> tt.count(2)
1
>>> tt.count(10)
0
(2)index 索引查找,返回最小索引
>>> tt=t+('python',)
>>> tt
(1, 2, 5, 'python', [1, 2, 'hello', 'python'], 'python')
>>> tt.index('python')
3
>>> tt.index('python',4,10)
2.2元组的索引与切片
>>> t=(1,2,5,'python',[1,2,'hello','python'])
>>> t
(1, 2, 5, 'python', [1, 2, 'hello', 'python'])
>>> t[1]
2
>>> t[-1]
[1, 2, 'hello', 'python']
>>> t[1::]
(2, 5, 'python', [1, 2, 'hello', 'python'])
>>> t[:-1]
(1, 2, 5, 'python')
>>> t(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
>>> t[1:]
(2, 5, 'python', [1, 2, 'hello', 'python'])
>>> t[::-1]
([1, 2, 'hello', 'python'], 'python', 5, 2, 1)
>>> t[:2]
(1, 2)
2.3元组的重复与连接
只有相同的数据结构类型才能进行连接,故只有元组才能与元组连接
>>> t * 2
(1, 2, 5, 'python', [1, 2, 'hello', 'python'], 1, 2, 5, 'python', [1, 2, 'hello', 'python'])
>>> t[-1]*3
[1, 2, 'hello', 'python', 1, 2, 'hello', 'python', 1, 2, 'hello', 'python']
>>> t[2:]*2
(5, 'python', [1, 2, 'hello', 'python'], 5, 'python', [1, 2, 'hello', 'python'])
>>> t+('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "str") to tuple
>>> t+('hello',)
(1, 2, 5, 'python', [1, 2, 'hello', 'python'], 'hello')
>>> t+[1,2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple
>>>
2.4 元组中的成员操作符(in)
>>> t
('haha', 20)
>>> 'haha ' in t
False
>>> 'haha' in t
True
>>> 20 in t
True
>>> 3 in t
False
2.5 元组的for循环
3.元组的应用场景
3.1 变量值交换
>>> a,b=(1,2)
>>> a
1
>>> b
2
>>> a,b=b,a
>>> a
2
>>> b
1
3.2多个变量的一次性赋值
>>> t=(1,2,3)
>>> a,b,c=t
>>> a
1
>>> b
2
>>> c
3
3.3 格式化输出应用
>>> t
(1, 2, 3)
>>> print("a=%d,b=%d,c=%d"%(1,2,3))
a=1,b=2,c=3
>>> print("a=%d,b=%d,c=%d"%(t))
a=1,b=2,c=3
>>>
>>> name='haha'
>>> age=20
>>> t=(name,age)
>>> t
('haha', 20)
>>> print("name:%s,age=%d"%(name,age))
name:haha,age=20
>>> print("name:%s,age=%d"%(t))
name:haha,age=20