python 元组

为什么需要元组?
比如:打印用户的姓名
userinfo1 = "fentiao 4 male"
userinfo[0:7]
结论:字符串中操作提取姓名/年龄/性别的方式不方便,诞生元组.


一.元组的定义:

元组(不可变数据类型)


- t = ()                                        定义空元组

- t = (1,)                                    元组只有一个元素时,加",",t=(1),t是int类型;
- t = (1,(1,2),'hello',[1,2])       可以包含任何类型的数据结构

python 元组

二.元组的特性


1.不可以修改元素内容

   t[0]="westos",直接报错

python 元组


2.分别赋值

name,age = ("westos",10)

python 元组


3.索引

python 元组


4.切片

python 元组


5.重复

python 元组

6.连接

python 元组


7.查看长度

python 元组


8.删除元组

python 元组


三.元组的常用操作方法


1.t.count()         计算某个元素出现的次数

python 元组


2.t.index()          返回某个值的最小索引

python 元组