1.创建空元组
temp1 = ();
如果元祖中只包含一个值,需用逗号隔开消除歧义
temp1=(1,)
2.元祖的基本操作
访问元祖,可以使用下标索引访问元素的值
temp1=('hello','world') print(temp1[1]) world temp1=(1,2,3,5,7,6) print(temp1[1:5]) (2, 3, 5, 7)
3.修改元祖
元祖中的元素值不允许修改,但可以对元祖进行连接组合
temp1=('hello','world') num =(2018,2) print(temp1+num) ('hello', 'world', 2018, 2)
4.删除元祖
元祖中的元素不允许删除,但可以使用del语句删除整个元祖 emp=('hello','world') del temp print(temp) Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled1/Class2String/vacation.py", line 26, in <module> print temp NameError: name 'temp' is not defined 此时元祖已被删除,输出变量会有异常
5.元祖的索引,截取
temp1=('hello','world','welcome') print(temp1[2]) welcome print(temp1[-2]) world print(temp1[1:]) ('world', 'welcome')
6. 元祖的内置函数
tup=('hello','world','welcome') print(len(tup)) # 用于计算元祖元素个数 # 3 tup =(2,7,2,9,4) print(max(tup)) # 用于求最大值 # 9 print(min(tup)) # 用于求最小值 # 2
7.tuple(seq) 用于将列表转换为元祖
tupl=['hello','world','welcome'] tup=tuple(tupl) print(tup) # ('hello', 'world', 'welcome')
8. 元祖的方法
tup=('hello','world','welcome') print(tup.index('hello')) # 获取hello的下标 # 0 print(tup.count('hello')) # 获取hello出现的次数 # 1