Python元組創(chuàng)建方法及特殊性解析
Python元組在實(shí)際應(yīng)用中可以在很大程度上幫助我們輕松的實(shí)現(xiàn)一些特定的功能需求。我們?cè)谶@里將會(huì)通過(guò)一些基本內(nèi)容的描述來(lái)為大家詳細(xì)介紹一下Python元組的正確應(yīng)用方法,希望可以給大家?guī)?lái)一些幫助。
創(chuàng)建及訪問(wèn)
- >>> mytuple=(1,2,3,4,'a')
- >>> mytuple
- (1, 2, 3, 4, 'a')
- >>> tuple('abcdefg')
- ('a', 'b', 'c', 'd', 'e', 'f', 'g')
- >>> mytuple[0]
- 1
- >>> mytuple[1:4]
- (2, 3, 4)
- >>> id(mytuple)
- 19758944
- >>> mytuplemytuple=mytuple+('b','c')
- >>> mytuple
- (1, 2, 3, 4, 'a', 'b', 'c')
- >>> id(mytuple)
- 19840112
- >>>
操作
- >>> mytuple =(1,2,3)
- >>> mytuple *2
- (1, 2, 3, 1, 2, 3)
- >>> 1 in mytuple
- True
- >>> 4 not in mytuple
- True
- >>> len(mytuple)
- 3
- >>> (1,2)==(2,1)
- False
- >>>
特殊性
1)不可變
- >>> mytuple=(1,2,3)
- >>> id(mytuple)
- 19773760
- >>> mytuple+=('a','b')
- >>> id(mytuple)
- 19758944
- >>>
默認(rèn)Python元組
1)所有的多對(duì)象的,逗號(hào)分隔的,沒(méi)有明確用符號(hào)定義。
- >>> 1,2,3,'a'
- (1, 2, 3, 'a')
2)所有函數(shù)返回的多對(duì)象
- >>> def f():
- return 1,2,3
- >>> f()
- (1, 2, 3)
單對(duì)象Python元組
- >>> a=('a')
- >>> type(a)
- < type 'str'>
- >>>
非要?jiǎng)?chuàng)建單對(duì)象元組,可以通過(guò)下面這種做法:
- >>> a=('a',)
- >>> type(a)
- < type 'tuple'>
列表和Python元組
元組不可變,即不會(huì)被篡改。
列表和元組可以相互轉(zhuǎn)換
- >>> mytuple=(1,2,3)
- >>> mytuple
- (1, 2, 3)
- >>> mylist=list(mytuple)
- >>> mylist
- [1, 2, 3]
- >>> tuple(mylist)
- (1, 2, 3)
以上就是我們對(duì)Python元組相關(guān)概念的介紹。
【編輯推薦】