python中的元組 Python中的元組

2021-10-11 11:47:27 字數 1313 閱讀 8914

一、元組(tuple)

元組基本上就像乙個不可改變的列表。與列表一樣支援任意型別的元素、支援巢狀以及常見的序列操作。元組也有一些方法,可用dir(tuple)檢視。

元組編寫在圓括號中。

>>> info = ('林間','man',1991,7,13,true) #支援不同型別

>>> info = ('林間','man',(1991,7,13),true) #支援巢狀

>>> info[0] #支援常見的序列操作

'林間'

>>> info[:2] #切片

('林間', 'man')

>>> info[1] = 'women'  #不可改變,對元組進行排序或重新賦值都是不行的

traceback (most recent call last):

file "", line 1, in

info[1] = 'women'

typeerror: 'tuple' object does not support item assignment

建立乙個元組,最重要的不是圓括號而是逗號

>>> tuple1 = (1) #單單只有圓括號不能建立乙個元組

>>> type(tuple1)

>>> tuple2 = 1,2,3 #加上逗號就能成功建立元組,圓括號不是必須的

>>> type(tuple2)

>>> tuple3 = 1, #建立單個元素的元組

>>> type(tuple3)

>>> tuple4 = () #建立空元組

>>> type(tuple4)

更新乙個元組。

之前說過元組是不可變的,所以只能通過切片、插入再覆蓋變數名的形式達到更新元組的目的。

>>> info = ('林間','man',(1991,7,13),true)

>>> info = info[:2] + (173,) + info[2:]  #實際上第一行中的元組並沒有消失,只是沒有變數名指向它了

>>> info

('林間', 'man', 173, (1991, 7, 13), true)

刪除元組。

通過del刪除整個元組

>>> info

('林間', 'man', 173, (1991, 7, 13), true)

>>> del info

>>> info

traceback (most recent call last):

file "", line 1, in

info

nameerror: name 'info' is not defined

元組 datawhale組隊學習python基礎

元組 定義語法為 元素1,元素2,元素n 與列表不同,元組是 列表是。t1 1 10.31 python t2 1,10.31 python print t1,type t1 1,10.31,python print t2,type t2 1,10.31,python tuple1 1 2,3 4,...

python中的元組

1 元組 列表中通常儲存相同型別的資料,而元組中通常儲存不同型別的資料 tuple 元組 與列表相似,不同之處在於元組的元素不能修改 元組表示多個元素組成的序列 元組在python開發中,有特定的應用場景 用於儲存一串資訊,資料之間使用,分隔 元組用 定義 2 元組的特點 t2 hello 要是沒有...

Python中的元組

元組是一種固定長度 不可變的python物件序列。1.建立 建立元組最簡單的方法就是用逗號分隔序列值。tup 4,5,6 tup 4,5,6 當你通過更複雜的表示式來定義元組時,通常需要用括號將值包起來.tup 2 4,5,6 7,8 tup 2 4,5,6 7,8 以上是生成了元素是元組的元組。2...