目录
注意:定义元组时,如果只有一个元素,元素后面一定要加逗号, 否则数据类型不确定
三、元组的特性(索引、切片、连接、重复、成员操作符、for循环)
一、元组的定义
元组(tuple):带了紧箍咒的列表
不可变数据类型,没有增删改,可以存储任意数据类型。
定义 一个元组
>>> t=(1,2,3,False,'hello')
>>> print(t,type(t))
((1, 2, 3, False, 'hello'), <type 'tuple'>)
定义一个空元组
>>> t=()
>>> print(type(t))
<type 'tuple'>
虽说,元组的内容不可以修改,但是如果元组里面包含可变的数据类型,可以间接的去修改元组内容
>>> t1=([1,2,3],4,5)
>>> print(t1,type(t1))
(([1, 2, 3], 4, 5), <type 'tuple'>)
>>> t1[0].append('hello')
>>> print(t1)
([1, 2, 3, 'hello'], 4, 5)
注意:定义元组时,如果只有一个元素,元素后面一定要加逗号, 否则数据类型不确定
>>> a=(1)
>>> print(type(a))
<type 'int'>
>>> a=(1,)
>>> print(type(a))
<type 'tuple'>
二、元组的常用方法
返回索引号,计算元素出现的次数
>>> t=(1,2,"hello")
>>> t2=('hello')
>>> print(t.index(t2)) #返回t2第一次在t中出现的索引号
2
>>> print(t.count('hello') #计算hello出现的次数
1
三、元组的特性(索引、切片、连接、重复、成员操作符、for循环)
t=(1,2,'hello','hello')
索引
>>> print(t[0])
1
切片
>>> print(t[::-1]) #倒序输出
('hello', 'hello', 2, 1)
>>> print(t[:2]) #输出前两个
(1, 2)
>>> print(t[:-1]) #输出除了最后一个元素
(1, 2, 'hello')
连接
print(t + (1,2,3,4))
注意:不同的数据类型之前 不能连接
>>> print(t+('hello','world'))
(1, 2, 3, 4, 'hello', 'world')
>>> print(t+[123,421])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple
重复
print(t * 20)
For循环
for i in t:
print(i)
成员操作符
print(1 in t)
print(1 not in t )
四、元组的应用场景
1、打包和解包
将若干个值全部赋给一个变量,就会将这些值打包成一个元组
将一个元组赋值给若干个变量,就会按照顺序将元组元素赋给若干个变量。
#打包
a = 1,2,3,4
print(type(a),a)
#输出
# <class 'tuple'> (1, 2, 3, 4)
#解包
i,j,k,f = a
print(i,j,k,f)
#输出
# 1 2 3 4
2、
a = 1
b = 2
a,b=b,a
实现原理:b,a =(1,2) b=(1,2)[0] a=(1,2)[1]
2、打印变量
name='yyz'
age=20
t=(name,age)
print("名字:%s,年龄:%d" %t)
用元组,就不用再用以前的方法
print("名字:%s,年龄:%d" %(name,age))
3、
五、元组与列表类型转换
t2 = tuple(t1) #直接将列表t1转换为元组,并赋给变量t2
t3 = list(t2) #直接将元组t2转换为列表,并赋值给t3