1.創建元組
# 創建元組
tuple1 = (1, 2, 'a', 'b' )
print('tuple1的值:{},tuple1的類型:{}'.format(tuple,type(tuple1)))
# 輸出結果 tuple的值:(1, 2, 'a', 'b'),tuple的類型:<class 'tuple'>
# 如果創建只有一個元素的元組時,要在元素後面加上逗號 如 tuple = (1,)
tuple2 = (1)
print('tuple2的值:{},tuple2的類型:{}'.format(tuple1,type(tuple2)))
# 輸出結果 tuple1的值:1,tuple1的類型:<class 'int'> 如果不加逗號,tuple1的類型時int
2.訪問元組
# 訪問元組
tuple1 = (1, 2, 'a', 'b' )
print('第一個元素:{},第二個元素:{}'.format(tuple1[0],tuple1[1]))
# 輸出結果 第一個元素:1,第二個元素:2
print('倒數第一個元素:{},倒數第二個元素:{}'.format(tuple1[-1],tuple1[-2]))
# 輸出結果 倒數第一個元素:b,倒數第二個元素:a
# 訪問時下標越界會報 IndexError: tuple index out of range 異常
3.修改元組的元素值
# 修改元組裏可變數據類型的元素
tuple1[2][0] = '1'
print('修改可變數據類型元素值後元組的id:{},修改後的值:{}'.format(id(tuple1), tuple1))
# 輸出結果 修改元素值後元組的id:2352507580480,修改後的值:(1, 2, ['1', 'b'])
# 修改元組裏不可變數據類型的元素
# tuple1[0] = 3
# print('修改不可變數據類型元素後元組的id:{},修改後的值:{}'.format(format(id(tuple1), tuple1)))
# 出現異常 TypeError: 'tuple' object does not support item assignment
# 個人總結: 元組中的不可變數據類型元素不能修改,可變數據類型元素可以修改(修改後內存地址不變)
4.元組的拼接和截取
# 重複n次元組元素
tuple1 = (1, 2)
n = 2
print(tuple1*2)
# 輸出結果 (1, 2, 1, 2)
# 元組的切片 從下標n開始到下標m結束 包含n下標的元素但不包含m下標的元素
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[1:3])
# 輸出結果 (2, 3)
# 如果tuple1[1:] 則是從下標1開始(包含)截取到尾部,如果寫成tuple1[:3]則是從開始截取到下標3(不包含)
5.查詢
# 判斷指定元素是否在元組中
tuple1 = (1, 2)
print(1 in tuple1) # 1在tuple1中返回True 不在返回False
# 輸出結果 True
print(3 not in tuple1) # 元素不在tuple1返回True 在就返回False
# 輸出結果True
# 獲取元組的長度
tuple1 = (1, 2, '1')
print('tuple1的長度是:{}'.format(len(tuple1)))
# 獲取元組中的最大值和最小值
tuple1 = (1, 2, '1')
# print('最大值:{}'.format(max(tuple))) 出現異常 not supported between instances of 'str' and 'int'
# str和int實例之間不支持,我想是不支持不同的數據類型
tuple2 = ('1', '2', '3', '4')
print('tuple2的最大值:{}'.format(max(tuple2)))
# 輸出結果 tuple2的最大值:4
print('tuple2的最大值:{}'.format(min(tuple2)))
# 輸出結果 tuple2的最大值:1
6.Tuple和List的相互轉換
# 元組和列表之間的相互轉換
tuple1 = (1, 2, 3, 4)
list1 = list(tuple1)
print('轉換後獲得的列表:{}'.format(list1))
# 輸出結果 轉換後獲得的列表:[1, 2, 3, 4]
tuple2 = tuple(list1)
print('轉換後獲得的元組:{}'.format(tuple2))
# 輸出結果 轉換後獲得的元組:(1, 2, 3, 4)
7.二維元組
# 二維元組,其實也是簡單的元組,就是元組裏面還是元組
tuple1 = ((1,2,3),(22,33),(100,200,300,400))
# 訪問二位元組的元素
print('一維元素:{},二維元素:{}'.format(tuple1[2],tuple1[0][1]))
# 輸出結果 一維元素:(100, 200, 300, 400),二維元素:2
可以看文檔瞭解更多和元組相關的函數 python中文文檔