目录
1、元组的基础元组的创建、相关序列操作、只有一个元组时该如何创建元组。
1、元组的基础元组的创建、相关序列操作、只有一个元组时该如何创建元组。
元组为不可变数据类型
#使用小括号创建元组
t=('hello',[10,20,30],'python','world')
print(t)
#使用内置函数tuple()创建元组
t=tuple('helloworld')
print(t)
t=tuple([10,20,30])
print(t)
#元组同样也是序列,所以关于序列的操作同样也适用元组
print('10在元组当中是否存在:',(10 in t))
print('10在元组当中是否存在:',(10 not in t))
print('最大值:',max(t))
print('最小值:',min(t))
print('len:',len(t))
print('t.index:',t.index(10))#10在这个元组中的索引
print('t.count:',t.count(10))#10在元组中出现的次数
#如果元组中只有一个元素
t=(50)
print(t,type(t))#元组中只有一个元素。不加逗号不会被识别为元组
y=(20,)
print(t,type(y))
#删除元组
del t
2、元组的访问及遍历,for、enumerate()函数
t=('hello','python','world')
#根据索引访问元组
print(t[0])
t2=t[0:3:2]#元组支持切片操作
print(t2)
#元组的遍历
for i in t:
print(i)
#for+range()+len()
for i in range(len(t)):
print(i,t[i])
#enumerate()
for i,k in enumerate(t,start=11):#序号从11开始
print(i,'----->',k)
3、元组生成器
3.1、用for循环来进行遍历
t=(i for i in range(1,4))
print(t)
t=tuple(t)
print(t)
#遍历
for item in t:
print(item)
3.2、用next函数
t=(i for i in range(1,4))
print(t.__next__())#取出第一个元素
print(t.__next__())#取出第二个元素
print(t.__next__())#取出第三个元素
t=tuple(t)#上一步的next已将t中所有的元素取出来了,此时在生成元组没有元素可用。
print()