Python 5 元組tuple使用

2021-10-25 09:31:54 字數 1493 閱讀 6061

除了list,元組tuple是python另一種有序的資料結構。tuple和list很相似,只是tuple初始化了之後就不能再修改其指向的元素。

定義tuple時,元素使用( )括起來,元素間用,隔開。

list使用[ ],注意對比區分。

>>

> tuple01 =

('12',12

,'花花'

)>>

> tuple01

('12',12

,'花花'

)

需要注意的是,當tuple中只有乙個元素時,要在元素後加,,如果不加逗號,括號會被認為是算術運算時的括號,此時定義的就不是乙個元組了,如tuple02:

>>

> tuple01 =(1

,)>>

> tuple01(1

,)>>

> tuple02 =(1

)>>

> tuple02

1

元組中也可以包含列表:

>>

> list01 =[1

,2,'3'

]>>

>

>>

> tuple03 =

('abc'

, list01,

'tt'

)>>

> tuple03

('abc',[

1,2,

'3']

,'tt'

)

獲取list01元素的方法類似c語言的二維陣列:

>>

> tuple03[1]

['modify',2

,'3'

]>>

> tuple03[1]

[0]'modify'

>>

> tuple03[1]

[2]'3'

由於元組初始化後就不能再修改,所以此時不能修改tuple03的任何乙個元素,但是可以修改列表list01的元素,因為修改list01並不會改變tuple03指向的元素,tuple03還是指向list01。

>>

> list01[0]

='modify'

>>

> tuple03

('abc',[

'modify',2

,'3'],

'tt'

)>>

>

>>

> tuple03[0]

='1'

traceback (most recent call last)

: file ""

, line 1,in

tuple03[0]

='1'

typeerror:

'tuple'

object does not support item assignment

python入門11 元組tuple

tuple元組是一種不可變資料型別,也是一種序列,因此可用序列的各類方法,比如切片和索引 coding utf 8 usr bin python 2018 11 03 dinghanhua 元組 元組,不可改變 賦值turple1 1,2turple2 3,4,a true print type t...

Python基礎(三) 元組tuple

python 的元組與列表類似,不同之處在於元組的元素不能修改,不可增加和刪除。元組使用小括號 列表使用方括號 元組建立很簡單,只需要在括號中新增元素,並使用逗號隔開即可。tup1 50 t type tup1 print t 結果 tup2 50,t type tup2 print t 結果 元組...

Python 3 7 元組 tuple 學習

元組 tuple 是 python 中常用的序列,它是不可修改的。定義元組tuple1 tuple2 hello python tuple3 hello python 2020 python 是完全動態資料型別,同乙個元組元素型別可以是多種的 print tuple1 hello python 獲取...