用書 PYTHON王者歸來 作者洪錦魁
元組的定義
numeber = (1,2,2,4,5)
names = (“Lisa”,”Ruby”,”Susan”)
numeber_names =(15,”susu”,”kiki”)
print(numeber)
print(names)
print(numeber_names)
print(type(numeber))
print(type(names))
print(type(numeber_names))
執行結果
執行結果
讀取元組元素
numeber = (1,2,2,4,5)
numeber1 = (1,)
names = (“Lisa”,”Ruby”,”Susan”)
numeber_names =(15,”susu”,”kiki”)
print(numeber[1])
print(names[2])
print(numeber[0],names[0])
x,y = 8,9
print(x,y)
執行結果
遍歷
names = (“Lisa”,”Ruby”,”Susan”)
for name in names:
print(name)
執行結果
修改元組
元組不可做更改,必須重新定義
執行結果
重新定義
names = (“Lisa”,”Ruby”,”Susan”)
print(names[2])
names = (“Lisa”,”Ruby”,”Kiki”)
print(names[2])
執行結果
元組切片
names =(“Lisa”,”Ruby”,”Susan”,”kIKI”,”Helen”)
print(names[1:3])print(names[:3])
print(names[0:])
print(names[-2:])
print(names[0:4:2])
執行結果
元組的函數
不適用POP() APPEND() 減少元組元素或增加元組元素
但可以用LEM()來列出長度
names = (“Lisa”,”Ruby”,”Susan”,”kIKI”,”Helen”)
print(len(names))
name =names.pop()
print(name)
name1 =names.append(“Luby”)
print(name1)
執行結果
List &Tuple 的元素互換
names = (“Lisa”,”Ruby”,”Susan”,”kIKI”,”Helen”)
name = list(names)
name.append(“Luby”)
print(name)
執行結果
執行結果
元組MAX MIN
執行結果
ENUMERATE
names = [“Lisa”,”Ruby”,”Susan”,”kIKI”,”Helen”]
name = enumerate(names)
lis = list(name)
print(lis)
print(type(lis))
print(type(lis[0]))
執行結果
names = (“Lisa”,”Ruby”,”Susan”,”kIKI”,”Helen”)
for name in names:
print(name)
for name, Count in enumerate(names):
print(name,Count)
for name in enumerate(names,5):
print(name)
for name, Count in enumerate(names,5):
print(name,Count)
執行結果
打包ZIP 解包
names = [“Lisa”,”Ruby”,”Susan”,”kIKI”,”Helen”]
number = [1,2,3,4,5]
ZIP = zip(names,number)
print(type(ZIP))
LIS = list(ZIP)
print(LIS)
names0 , number0 = zip(*LIS)
print(names0)
print(number0)
執行結果
group1 = (1,2,3)
group2 = (4,5,6)
group3 = (7,8,9)
group = zip(group1,group2,group3)
print(tuple(group))
執行結果
filed = [“Hiroshima”,”okinawa”,”Yokyo”,”fukuoka”]
Info = [100,95,45,99
]ZIP = zip(filed,Info)
lis = list(ZIP)
for city, info in lis:
print(city,info)
f,i = zip(*lis)
print(f)
print(i)
執行結果
大型元組
group1 = [1,2,3]
group2 = [4,5,6]
group3 = [7,8,9]
group = group1,group2,group3
print(type(group))
print(group)
執行結果