#1,定义元组
t = (1,2,3,‘abc‘)
print t
#2,定义只有1个元素的元组
#括号里加个逗号消除歧义
t = (1,)
#3,访问元组
t = (1,2,3,‘abc‘)
print t[3]
print t[:]
print t[1:3]
print t[:3]
print t[1:]
#4,修改
#不允许修改,以下程序会报错
#t = (1,2,3,‘abc‘)
#t[0]= 4
#5,合并
t1 = (1,2,3,‘abc‘)
t2 = (‘def‘,)
t1 = t1 + t2
print t1
#6,删除
#元组值不能删除,但整个元组可以删掉
t = (1,2,3,‘abc‘)
print t
#del t
print ‘after del t‘,t
#7,元组运算符
t = (1,2,3)
print t*2
print t+t+t
#8,不带括号的元组
x,y = 1,2
print x
(x,y) = (1,2)
print x
#9,内置函数
#cmp() 比较两个元组,一样就返回0,不一样就返回-1
t1 = (1,2)
t2 = (3,4)
t3 = (1,2)
print cmp(t1,t2)
print cmp(t1,t3)
#len() 返回元素个数
t1 = (1,2,3,4,5,6)
print len(t1)
#max() 返回元组中元素最大值
t1 = (1,2,3,4,5,6)
t2 = (‘a‘,‘b‘,‘c‘)
print max(t1)
print max(t2)
#min()用法同max(),返回元组中元素最小的值
#tuple() 把list转换成tuple
list = [1,2,3]
print tuple(list)
时间: 2024-12-28 13:25:31