python 元組操作和序列的公共操作

元組 tuple

元組裏面可以包含各種類型的數據 整數、字符串、列表、元組、布爾值、True、False

空元組t1=()

元組只有1個元組,要在元組後面加, t2=(1,)

‘’'元組中也可以加嵌套的元素, 建議不要在元組中添加可變類型(列表、字典)

取值方式:切片 單個值:元組名[索引值] 嵌套取值(剝洋蔥)

t1=(1,0.9,'yes','False',(1,4,'hello','world'))
print(len(t1))
print(t1[-1]) #(1, 4, 'hello', 'world')
print(t1[2][-1]) #s
print(t1[4][3][1]) #o

#切片
# 把索引值爲偶數的打印出來
print(t1[::2])
print(t1[:5:2])

#元組是有序數組,但不能做增刪改
print(t1.count(1)) #不會統計(1, 4, 'hello', 'world')
print(t1.index(1,0))#取數字爲1的第二個元素位置, index默認爲索引爲0開始

#序列類型均支持的公共操作
#1、數字索引取值
#2、切片操作
#3、成員關係操作
#4、in 或者 not in

food=('break','oil','banana','orange')
print('oil' in food)  #True
print('orange' not in food) #False

#5、連接
#同類型才能連接
new_tuple=('rose','jack')
print(new_tuple+food) #('rose', 'jack', 'break', 'oil', 'banana', 'orange')

#6、重複操作 序列類型*整數
print(new_tuple*2) #('rose', 'jack', 'rose', 'jack')

#7、遍歷操作 for循環
for item in food:    
    print(item)
    
#8、拆包
my_tuple='love','字符串'
print('{}的類型是{}'.format(my_tuple,type(my_tuple))) #<class 'tuple'>

#元組拆包
str1,str2=my_tupleprint('str1:',str1)print('str2:',str2)

#字符串拆包
my_str="Helayel"
str0,str1,str2,str3,str4,str5,str6=my_str
print('str0:', str0)
print('str6:',str6)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章