點擊藍色「潭時錄」關注我丫
加個「星標」,每天和小潭一起快樂的學習
你好,我是在學python的小潭。通過前兩天的文章10-python中的字典我們學習了有關字典的知識,今天我們將學習一下python中的元組。
(一)元組介紹
元組(),是python內置的數據結構之一,是一個不可變序列。
可變序列和不可變序列區分標準:
不可變序列沒有增刪改的操作
可變序列在對序列中的元素進行增刪改操作時,對象地址不發生改變
代碼示例:
lst = [11, 22, 33]print('增加前:', lst, id(lst))lst.append(44)print('增加後:', lst, id(lst))
s = '小潭'print(s, id(s))s = s + '學python'print(s, id(s))結果輸出:
增加前:[11, 22, 33] 49033928增加後:[11, 22, 33, 44] 49033928小潭 49183392小潭學python 49248984(二)元組創建方式
元組創建可以通過以下三種方式:
t = ('小潭', '學', 'python', 666)t = tuple( ('小潭', '學', 'python', 666) )代碼示例:
t = ('小潭', '學', 'python', 666)print('使用()創建:', t, type(t))
t2 = '小潭', '學', 'python', 666print('可省略():', t2, type(t2))
t1 = tuple(('小潭', '學', 'python', 666))print('使用tuple():', t1, type(t1))
t3 = ('python') t4 = ('python', )print('單個元素沒有,逗號:', t3, type(t3))print('單個元素有,逗號:', t4, type(t4))
t5 = ()t6 = tuple()print('空元祖創建:', t5)print('空元祖創建:', t6)結果輸出:
使用()創建:('小潭', '學', 'python', 666) <class 'tuple'>可省略():('小潭', '學', 'python', 666) <class 'tuple'>使用tuple():('小潭', '學', 'python', 666) <class 'tuple'>單個元素沒有,逗號:python <class 'str'>單個元素有,逗號:('python',) <class 'tuple'>空元祖創建:()空元祖創建:()(三)元組的不可變特性
元組是不可變序列,因此在多任務環境下,同時操作對象時不需要加鎖[在程序中儘量使用不可變序列]。
注意事項:元組中存儲的是對象的引用。
代碼示例:
t = ('小潭', ['學', 'python'], 666)print('原始元祖:', t, type(t))print('元素1:', t[0], type(t[0]), id(t[0]))print('元素2:', t[1], type(t[1]), id(t[1]))print('元素3:', t[2], type(t[2]), id(t[2]))t[1].append(888)print(t)結果輸出:
原始元祖:('小潭', ['學', 'python'], 666) <class 'tuple'>元素1:小潭 <class 'str'> 14512880元素2:['學', 'python'] <class 'list'> 14364776元素3:666 <class 'int'> 14573184('小潭', ['學', 'python', 888], 666)(四)元組的遍歷
元組是可迭代對象,可以使用for-in進行遍歷。
代碼示例:
t = ('小潭', ['學', 'python'], 666)print('---使用索引----')print(t[1])
print('---for-in遍歷---:')for item in t: print(item)結果輸出:
---使用索引----['學', 'python']---for-in遍歷---:小潭['學', 'python']666以上是python中有關元組的定義和相關操作的介紹,下期我們將學習python中集合的知識,敬請期待。
下期預告:python中的集合