Python3 列表List或元組tuple中元素分解(賦值操作)
阿新 • • 發佈:2019-01-22
元組示例:
p = (1,2,3,4,5,6,7,)
a,b,c,d,e,f,g = p
print (a,b,c,d,e,f,g)
輸出:1 2 3 4 5 6 7
注意:變數總數和結構要與序列相吻合。
列表示例:
data = ['難免有錯', 120 , 60, (2015, 8, 7) ]
name, shares, price, date = data
print(name, shares, price, date)
輸出:難免有錯 120 60 (2015, 8, 7)
物件可迭代就可以執行分解操作,並非只有列表和元組:
示例:
s = 'whoareyou' a,b,c,d,e,f,g,h,i = s print(a,b,c,d,e,f,g,h,i)
輸出:w h o a r e y o u
我們可以選擇想要用到的元素進行特別命名,對不需要的元素用一個不常見變數名代替
如:
s = 'whoareyou'
a,X,c,X,e,X,g,X,X = s
print(a,c,e,e,g)
輸出:w o r r y
程式碼參考自:Python Cookbook 中文第三版