元組?
在Python 2 ň
>>> zip(*2*[iter(x)])
[(0, 1), (2, 3), (4, 5), (6, 7)]
在Python 3 ň
zip()
表現略有不同...
>> zip(*2*[iter(x)])
<zip object at 0x285c582c>
>>> list(zip(*2*[iter(x)])])
[(0, 1), (2, 3), (4, 5), (6, 7)]
名單?
執行是在Python 2和3一樣的...
>>> [[i,j] for i,j in zip(*2*[iter(x)])]
[[0, 1], [2, 3], [4, 5], [6, 7]]
,或者:
>>> [list(t) for t in zip(*2*[iter(x)])]
[[0, 1], [2, 3], [4, 5], [6, 7]]
,如果你想分成list
S的3後者是更有益或多種元素,而不拼寫出來,如:
>>> [list(t) for t in zip(*4*[iter(x)])]
[[0, 1, 2, 3], [4, 5, 6, 7]]
如果zip(*2*[iter(x)])
對你來說看起來有點奇怪(當我第一次看到它時,它確實對我有用!),看看How does zip(*[iter(s)]*n)
work in Python?。
另請參閱this pairwise implementation,我認爲它很整潔。
你說二元組,但你的例子是「雙列表」 – 2011-05-15 10:14:09
重複(很多次):http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-重複列表塊 – tokland 2011-05-15 10:15:14
當然,糟糕的是混淆。儘管這個問題並不重要;) – c089 2011-05-15 10:28:43