Python-33 - 陣列介紹 - tuple()元組 使用說明

Tuple()元組 使用說明

Tuple-元組3特點

  1. 有序號
  2. 允許重覆
  3. 不可更改組的資料

使用for迴圈讀出一筆筆的資料

讀出tuple資料共有幾筆


 

 tuple()有兩種表示方式


it3c =("mouse","computer","monitor","notebook")
print(it3c)

myclass = tuple(("java","python","RWD","PS"))
print(myclass)

看看效果

Tuple-元組3特點

  1. 有序號 (序號調出資料)
  2. 允許重覆
  3. 不可更改組的資料

使用方式與 list 相同

myclass = tuple(("java","python","RWD","PS"))
print(myclass)

#有序號
print(myclass[1]) #python

#允許重覆
myclass = tuple(("java","python","RWD","PS","PS"))
print(myclass)#('java', 'python', 'RWD', 'PS', 'PS')

3.list()可以更改組的資料,但tuple()不可更改組的資料,所以會跳出錯誤訊息

(不可更改組的資料,所以也無法新增、修改、刪除資料)

#list 可以接受更改組的資料
M2 = ["A","B","C","D","E"]
C=M2[4]="EEE"
print(M2) #['A', 'B', 'C', 'D', 'EEE']

#tuple 不可以接受更改組的資料
M2 = ("A","B","C","D","E")
C=M2[4]="EEE"
print(M2) 
#錯誤訊息
"""
Traceback (most recent call last):
  File "tuple_1.py", line 27, in <module>
    C=M2[4]="EEE"
TypeError: 'tuple' object does not support item assignment
"""

看看效果

 

使用for迴圈讀出一筆筆的資料
it3c =("mouse","computer","monitor","notebook")

for a in it3c :
    print(a) 

myclass = tuple(("java","python","RWD","PS"))

for b in myclass:
    print(b)

看看效果

讀出tuple資料共有幾筆
#讀出tuple資料共有幾筆
it3c =("mouse","computer","monitor","notebook")
print(len(it3c))#4筆
myclass = tuple(("java","python","RWD","PS","DW"))
print(len(myclass))#5筆

看看效果

使用del刪除資料時

因為不能tuple更改組的資料,所以使用del 陣列變數[2] 刪除第2個位置的資料,會出現錯誤

myclass = tuple(("java","python","RWD","PS","DW"))
del myclass[2]
print(myclass)

只能刪除全部 del 變數名稱,把整個tuple()資料全部刪除,連變數名字也會一起刪除,所以找不到變數會引發錯誤

myclass = tuple(("java","python","RWD","PS","DW"))
del myclass
print(myclass)

看看效果

 

 

YiruAtStudio - 關於我