Python學習之Part06.元組

元組:元組也是一種數據類型,其中可以存儲任意數據類型,但是元組不能修改

1.元組的創建:

創建一個空元組

>>> t = ()
>>> print(type(t))
<class 'tuple'>

>>> t = tuple()
>>> type(t)
<class 'tuple'>

創建並初始化一個元組

>>> t1 = ([1, 2, 3], 'hello', '1.34')
>>> print(t1, type(t1))
([1, 2, 3], 'hello', '1.34') <class 'tuple'>

如果元組中只有一個元素,則創建時必須加逗號,否則數據類型不確定

>>> t2 = (1)
>>> t3 = (1,)
>>> t4 = ('s')
>>> print(type(t2), type(t3), type(t4))
<class 'int'> <class 'tuple'> <class 'str'>

如果元組裏麪包含可變的數據類型 可以間接的去修改元組的內容

>>> t1 = ([1, 2, 3], 4, 5, 6)
>>> t1
([1, 2, 3], 4, 5, 6)
>>> t1[0].append(7)
>>> t1
([1, 2, 3, 7], 4, 5, 6)
>>> type(t1)
<class 'tuple'>

強制類型轉換

>>> li = [] 
>>> t = tuple(li)
>>> print(type(li), type(t))
<class 'list'> <class 'tuple'>
>>> li_1 = list(t)
>>> type(li_1)
<class 'list'>

2.元組的特性

>>> t = (1, 2, 'hello', 2, 3)

索引:

>>> print(t[0])  
1
>>> print(t[-1])
3

切片:注意所選擇的區間爲左閉右開區間

>>> print(t[1:])
(2, 'hello', 2, 3)
>>> print(t[:-1])
(1, 2, 'hello', 2)
>>> print(t[::-1])
(3, 2, 'hello', 2, 1)
>>> print(t[1:3])
(2, 'hello')

連接:注意不同類型的不能連接

>>> t1 = ('hello',)
>>> print(t + t1)
(1, 2, 'hello', 2, 3, 'hello')

>>> print(t + 'hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "str") to tuple
>>> print(t + [1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple

重複:

>>> print(t * 2)
(1, 2, 'hello', 2, 3, 1, 2, 'hello', 2, 3)

成員操作符:

>>> print('hello' in t)
True
>>> print('python' in t)
False

for 循環:

>>> for i in t:
... 	print(i)
... 
1
2
hello
2
3

3.元組的常用方法

index()返回元組中元素的索引,若元素存在,則返回索引,若不存在,則報錯

>>> t = (1, 2, 'hello', 2, 3)
>>> t.index('hello')
2

count()查找所傳遞參數在元組中的數目,若存在,則返回數目,若不存在,則返回0

>>> t.count(2)
2
>>> t.count('hello')
1

4.元組的應用場景

交替賦值

>>> a = 1
>>> b = 2
>>> a,b = b,a   # 實現:a,b=(1,2) b=(1,2)[0] a =(1,2)[1]
>>> print(a, b)
2 1

打印變量

>>> name = 'test'
>>> age = 18
>>> t = (name, age)
>>> print('name=%s, age=%d' %(name, age))
name=test, age=18
>>> print('name=%s, age=%d' %t)
name=test, age=18

>>> print('name=%s' %name)
name=test
>>> print('age=%d' %age)  
age=18
>>> print('part=%s' %part)
part=linux
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章