學習python的資料型別——元組

南夏一木子發表於2020-12-13

一、學習python資料型別-元組

1、元組

  • 定義:()內以逗號分隔,按照索引,存放各種資料型別,每個位置代表一個元素。

  • 元組的特點:

    1、可存放多個值;
    2、按照從左到右的順序定義列表元素,下標從0開始順序訪問,有序;
    3、不可修改指定索引位置對應的值,不可變。

1.1、元組的建立,可參考如下方式:
### 方式一:
In [32]: students = ("小花",1,2,3,4,"jj","ll","ff",3,8,9)
In [33]: students
O≥ut[33]: ('小花', 1, 2, 3, 4, 'jj', 'll', 'ff', 3, 8, 9)
### 方式二:
In [34]: teachers = tuple(("gg","ff","zz",4,6,8,9,20))
In [35]: teachers
Out[35]: ('gg', 'ff', 'zz', 4, 6, 8, 9, 20)
1.2、元組的常規方法,索引、切片、迴圈、長度、包含等
1.2.1、索引,主要通過索引取出特定的值
In [32]: students = ("小花",1,2,3,4,"jj","ll","ff",3,8,9)
In [37]: students[2]
Out[37]: 2
In [38]: students[7]
Out[38]: 'ff'
######## 如果取一個超出下標的值會有提示 ########
In [39]: teachers[8]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-39-22964f3852b0> in <module>
----> 1 teachers[8]

IndexError: tuple index out of range
1.2.2、切片,可以看做將一塊麵包切成很多塊麵包,公式為:tupleName[start : end : step],示例如下:
In [47]: teachers
Out[47]: ('gg', 'ff', 'zz', 4, 6, 8, 9, 20)
In [46]: teachers[2:9]
Out[46]: ('zz', 4, 6, 8, 9, 20)
In [48]: teachers[1:20]			# 雖然末尾超出了teacher元組的下標,但是不會報錯
Out[48]: ('ff', 'zz', 4, 6, 8, 9, 20)
In [49]: teachers[-1:]			# 切片從左到右,因此只有20這一個元素
Out[49]: (20,)
In [50]: teachers[:-1]
Out[50]: ('gg', 'ff', 'zz', 4, 6, 8, 9)
In [51]: teachers[::-1]			# 反轉
Out[51]: (20, 9, 8, 6, 4, 'zz', 'ff', 'gg')
In [52]: teachers[2:5:-1]
Out[52]: ()
In [53]: teachers[2:-1:-1]
Out[53]: ()
In [54]: teachers[2:-1:1]
Out[54]: ('zz', 4, 6, 8, 9)
In [62]: teachers[-4:2:1]
Out[62]: ()
1.2.3、長度,使用len()方法實現,示例如下:
In [47]: teachers
Out[47]: ('gg', 'ff', 'zz', 4, 6, 8, 9, 20)
In [63]: len(teachers)
Out[63]: 8
1.2.4、通過元素取下標,使用.index()函式,示例如下:
In [47]: teachers
Out[47]: ('gg', 'ff', 'zz', 4, 6, 8, 9, 20)
In [64]: teachers.index("zz")
Out[64]: 2
In [65]: teachers.index(20)
Out[65]: 7

1.2.5、計算一個元素在這個元組中出現的次數,使用.count()函式,示例如下:
In [47]: teachers
Out[47]: ('gg', 'ff', 'zz', 4, 6, 8, 9, 20)
In [66]: teachers.count("gg")
Out[66]: 1
In [67]: teachers.count(8)
Out[67]: 1

1.2.6、判斷一個元素是否在某個元組中,使用in關鍵字,示例如下:
In [47]: teachers
Out[47]: ('gg', 'ff', 'zz', 4, 6, 8, 9, 20)
In [68]: print("gg" in teachers)
True
In [69]: print("mm" in teachers)
False
1.2.7、迴圈元組,使用for迴圈,示例如下:
In [72]: for i in teachers:
    ...:     print(i, end=" ")
gg ff zz 4 6 8 9 20 
1.3、元組與列表之間的相互轉換,按照如下示例進行轉換:
1.3.1、將元組轉換為列表,使用list()方法,示例如下:
In [74]: type(teachers)
Out[74]: tuple
In [75]: teachers = list(teachers)
In [76]: type(teachers)
Out[76]: list
1.3.2、將列表轉換為元組,使用tuple()方法,示例如下:
In [77]: list1 = [1,4,6,1,3,4,4,"ww","vv","ww"]
In [78]: type(list1)
Out[78]: list
In [79]: list1 = tuple(list1)
In [80]: type(list1)
Out[80]: tuple
1.4、元組的其他特性
In [82]: st =(1,2,3,4,5,65,6,7)
In [83]: sum(st)			# 對純數字的元組進行求和操作
Out[83]: 93

相關文章