看板 Python 關於我們 聯絡資訊
※ 引述《WaiTingKuo (:!)》之銘言: : In [12]: a = [1, 2, 3, 4, 5, 6] : In [13]: for x, y, in zip(*[iter(a)]*2): : ....: print x, y : ....: : 1 2 : 3 4 : 5 6 這麼高段的技巧當然不是我想出來的啦XD 之前在看python document的時後覺的蠻好用的就記下來了 http://docs.python.org/2/library/functions.html#zip 基本上的想法就是把同個iterator丟兩份到zip裡面 等價於 In [16]: b = iter(a) In [17]: zip(b, b) Out[17]: [(1, 2), (3, 4), (5, 6)] 至於第一個* 那個叫Unpacking Argument Lists http://docs.python.org/2/tutorial/controlflow.html#arbitrary-argument-lists 我不太清楚中文有沒有什麼好名字,反正就是把list展開一個一個丟到function裡 In [18]: def f(a, b, c): ....: print a, b, c ....: In [19]: f(*[1, 2, 3]) 1 2 3 放在這裡的好處就是少寫一行 一開始可能看起來怪怪的,看久了會比寫兩行更直覺 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.43.138.63
tjjh89017:這比較數學一點吧 07/12 22:52
EntHeEnd:Thx 07/13 16:35