Python課程學習——元組

元組和列表類似,同一個元組中可以沒有數據,也可以有多種數據
區別:
(1)定義方式不一樣,列表使用[],元組使用()
(2)元組中的元素不能改變,一旦創建就不能再對其中的元素進行增、刪、改操作,只能訪問

注意:
(1)如果元組只有一個元素,那麼這個元素後面要加逗號,如tuple2,否則將被認爲是一個基本數據類型而不是元組
(2)創建元組可以沒有括號,元素之間用逗號隔開

#1、創建元組 同一個元組中可以存放任務數據類型
tuple1=();
tuple2=(12,);
tuple3=(1,1.1,‘a’,3+4j);
tuple4=(1,2,3,4,5);
tuple5=4,5,6,7;

#2、訪問元組元素 通過索引訪問
print(“訪問元組單個元素tuple4[2]:”,tuple4[2]);
print(“訪問元組多個元素tuple4[0:2]:”,tuple4[0:2]);

print("");

#3、內建方法
print(“tuple4:”,tuple4);
print(“元組長度即元組元素個數len(tuple4):”,len(tuple4));
print(“元組元素最大值max(tuple4):”,max(tuple4));
print(“元組元素最小值min(tuple4):”,min(tuple4));
print(“元組中某個元素出現的次數tuple4.count(a):”,tuple4.count(‘a’));
print(“元組中某個值第一次出現的索引位置tuple4.index(1):”,tuple4.index(1));
print(“元組中某個值第一次出現的索引位置tuple4.index(2,0,2):”,tuple4.index(2,0,2));

注意:
print("元組中某個值第一次出現的索引位置tuple4.index(a,0,2):",tuple4.index('a',0,2));
Traceback (most recent call last):
  File "D:\Epan\selfstudy\pythonStudy\helloPython\helloPython\YuanZuPython.py", line 38, in <module>
    print("元組中某個值第一次出現的索引位置tuple4.index(a):",tuple4.index('a'));
ValueError: tuple.index(x): x not in tuple

print("");

#4、元組拼接
print(“tuple4:”,tuple4);
print(“tuple5:”,tuple5);
print(“元組拼接tuple4+tuple5:”,tuple4+tuple5);

#5、元組乘法
print("元組乘法tuple42:",tuple42);

#6、判斷元素是否存在於元組中
print(“2 in tuple4?”,2 in tuple4);

#7、迭代

for ele in tuple4:
    print(ele);

#8、元組嵌套
tuple6 = [tuple4,tuple5];
print(“元組嵌套tuple6:”,tuple6);

執行結果:
訪問元組單個元素tuple4[2]: 3
訪問元組多個元素tuple4[0:2]: (1, 2)

tuple4: (1, 2, 3, 4, 5)
元組長度即元組元素個數len(tuple4): 5
元組元素最大值max(tuple4): 5
元組元素最小值min(tuple4): 1
元組中某個元素出現的次數tuple4.count(a): 0
元組中某個值第一次出現的索引位置tuple4.index(1): 0
元組中某個值第一次出現的索引位置tuple4.index(2,0,2): 1

tuple4: (1, 2, 3, 4, 5)
tuple5: (4, 5, 6, 7)
元組拼接tuple4+tuple5: (1, 2, 3, 4, 5, 4, 5, 6, 7)
元組乘法tuple4*2: (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
2 in tuple4? True
1
2
3
4
5
元組嵌套tuple6: [(1, 2, 3, 4, 5), (4, 5, 6, 7)]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章