1 什么是元組
Python中元組與串列類似,只是元組的元素不能更改
元組的創建很簡單,使用圓括號()將元素括起來即可,雖然不用括號也可以,但不建議這么做
特別的是元組只有一個元素時,需要在元素后面加一個逗號,不然括號會被當成運算子,示例如下:
tuple1 = () # 創建空元組
tuple2 = ('a') # 單個元素后不加逗號無法創建
tuple3 = ('a',) # 單個元素后要加逗號
tuple4 = ('a', 'b') # 多個元素逗號隔開
tuple5 = 'a', 'b' # 不適用()也可以創建元組,但不建議使用
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
print(tuple5)
結果如下:

2 元素的操作
元組除了元素不能修改之外,其余的操作同串列,示例如下:
tuple1 = ('張無忌', '成昆', '楊逍')
tuple2 = ('趙敏', '滅絕大師')
tuple3 = tuple1 + tuple2 # 元組拼接
tuple4 = tuple1 * 3 # 復制元素
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
print(tuple1[1]) # 訪問元組元素
print(tuple1[0:2]) # 元組切片
結果如下:

除了上面的操作外,元組也有類似串列的內置函式和方法:
-
len(tuple):計算元組元素個數
-
max(tuple):回傳元組元素最大值
-
min(tuple):回傳元組元素最小值
-
tuple(iterable):將可迭代物件轉為元組
-
item in tuple:判斷元素item是否存在
-
for item in tuple:遍歷元組元素
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/281943.html
標籤:Python
下一篇:Python 條件控制
