python-進階教程-資料結構的分解
阿新 • • 發佈:2018-12-18
0.摘要
本文主要介紹python中常用資料結構的分解方法。
1.可迭代物件分解為多個變數
任何可迭代物件都可以通過簡單的賦值操作分解為單獨的變數,唯一的要求是變數的總數和結構要與可迭代物件相吻合。
數量不匹配會報錯。
data = [2018,'December',6,'Thursday']
year, month, day, weekday = data
print(year,month,day,weekday)
#result:2018 December 6 Thursday
字串也是可迭代物件,所以按照上述說法,字串也是可以拆分的:
s = "Hello" a, b, c, d, e = s print(a,b,c,d,e) #result:H e l l o
這裡介紹一個技巧:對於不想儲存的變數,可以將其賦值給一個不會用到的變數名。注意,要確保這個變數名在程式中是不會被用到的。通常情況,使用"_"儲存想要丟棄的變數。
text = ['start','text1','text2','text3','end']
_, text1, text2, text3, _ = text
print(text1, text2, text3)
2. 任意長度的可迭代物件
在上一節中提到,可迭代物件分解的條件為:變數的總數和結構要與可迭代物件相吻合
如果分解的值過少,會報出:need more values to unpack 的錯誤;
如果分解的值過多,會報出:too many values to unpack 的錯誤。
對於數量不確定問題,可以嘗試使用“*表示式”解決,“*表示式”能夠匹配任意數量的變數。
group = ["tomato omelette", "tomato", "egg", "salt", "peanut oil",10.0 ]
dish, *ingredient, price= group
print(ingredient)
#result:['tomato', 'egg', 'salt', 'peanut oil']
可見,“*表示式”能夠根據前後變數數目,自適應匹配分解的變數數。
另外,“*表示式”還可以列表切分:
sales_record = [10,9,10,11,8,15,12,6,18]
*trailing_qtrs, current_qrt = sales_record
trailing_avg = sum(trailing_qtrs) / len(trailing_qtrs)
print(trailing_avg,current_qrt)
#result:10.125 18
通過“*表示式”,我們將資料分為歷史資料和當前資料兩部分,當然這與sales_record[:-1],sales_record[1]效果是一樣的。
利用這一點,可以實現精巧的遞迴結構:
items = [1,2,3,4,5,6,7,8,9,10]
def sum(items):
head, *tail = items
return head + sum(tail) if tail else head
print(sum(items))
另外,“*表示式”在迭代一個變長的元組序列時候尤其有用,例如:
def my_add(x,y):
return x + y
def my_square(x):
return x ** 2
orders = [
("add",1,2),
("square",3),
("add",4,5)
]
for tag, *args in orders:
if tag == "add":
print(my_add(*args))
elif tag == "square":
print(my_square(*args))
*args對一些帶有預設引數值進行封裝的時候非常有用,這可以使得我們不會被介面引數的數量問題所困擾。