一、特点
1、任意对象有序集合;
2、通过下标访问;
3、属于“不可变”类型;
4、长度固定,任意类型,任意嵌套
二、声明
1、用括号(元素,)
例如 (1,2)
(1,2)+(3,4)=(1,2,3,4) #tuple相加
2、不用括号
例如 1,2
3、声明一个元素的tuple
(1)a=(40,)
(2)a=40,
三、基本操作
1、元素的修改,不支持原位改变
(1)类似与字符串的修改
x =(1,2,3,4)
for c in x:
print(c2)
输出的结果为
1
4
9
16
(2)转换为列表
x =(1,2,3,4)
res =[]
for a in x:
res.append(a2)
(3)
x =(1,2,3,4)
res =[t**2 for t in x]
2、索引元素的位置.index()
3、统计元素的个数.count()
四、nametuple
from collections import nametuple
Employee =nametuple(‘Employee’,[‘name’,‘age’,‘department’,‘salary’])
jerry =Employee(‘Jerry’,age=30,department=‘财务部’,salary=100)
元组tuple
最新推荐文章于 2022-07-01 14:38:01 发布