Python Cookbook (1-1) 簡單拆分

1. List:

快速建構 List。

lst = [i for i in range(10)]
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

lst = [i for i in range(10) if i %2 == 0]
Out: [0, 2, 4, 6, 8]

2. 拆分:

對 iterable 的物件可進行拆分,拆分時元素要符合即可。

cooper = ["bear", 180, 60, (2018, 4, 29)]
name, height, weight, birthday = cooper

print(name, height,weight, birthday)
Out: bear 180 60 (2018, 4, 29)

拆分時也可以用 "_" 丟棄不需要的項目(這邊的丟棄並不是真的丟棄而是將變數命名為"_")。

name, _, weight, _ = cooper

對 list 中的 tuple 再拆分。

name, height, weight, (year, month, day) = cooper

3. 拆分成任意長度的元素:

name = ["alice", "bob", "cat", "dog"]
teamA, *teamB, teamC = name

"*" 會聰明地把拆分完對位剩的的元素回傳一個 list,所以 teamB 是 ["bob", "cat"]。

來把剩下不定長度的元素丟棄。

teamA, teamB, *_ = name


Reference

[1] David Beazley, Brian K. Jones, Python Cookbook, 3e , O'Reilly Media (2014)

留言

熱門文章