python之元組

元組的定義

定義空元組
>>> tuple = ()
>>> type(tuple)

一般元組
>>> tuple = ('ff',21,'girl')
>>> type(tuple)
<type 'tuple'>

元組特性

不能對元組的值任意更改
對元組分別賦值,引申對多個變量也可通過元組方式分別賦值

##不能更改
>>> a = ('heli',21,'girl')
>>> a
('heli', 21, 'girl')
>>> a[0]
'heli'
>>> a[-1]
'girl'
>>> a[0] = 'heyi'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment


##可以賦值
>>> name,age,gender = a
>>> print name
heli
>>> print age
21
>>> print gender
girl

元組的操作

元組也屬於序列,可執行的操作如下:
索引、切片、重複、連接和查看長度

>>> a
('heli', 21, 'girl')

##查看長度
>>> len(a)
3

##連接
>>> a1 = ('hrh',22)
>>> a2 = ('zrh',12)
>>> print a1 + a2
('hrh', 22, 'zrh', 12)

##索引
>>> a[1]
21
>>> a[0]
'heli'
>>> a[-1]
'girl'

##重複
>>> a = a*3
>>> a
('heli', 21, 'girl', 'heli', 21, 'girl', 'heli', 21, 'girl')

##切片
>>> a
('heli', 21, 'girl', 'heli', 21, 'girl', 'heli', 21, 'girl')
>>> a[0:7:2]
('heli', 'girl', 21, 'heli')

元組的刪除

只能用del

>>> a
('heli', 21, 'girl', 'heli', 21, 'girl', 'heli', 21, 'girl')
>>> type(a)
<type 'tuple'>
>>> del(a)
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
發佈了87 篇原創文章 · 獲贊 12 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章