作者WaiTingKuo (:!)
看板Python
标题Re: [问题] for回圈问题
时间Fri Jul 12 22:49:01 2013
※ 引述《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
1F:→ tjjh89017:这比较数学一点吧 07/12 22:52
2F:推 EntHeEnd:Thx 07/13 16:35