我想转换这样的列表
l1 = [1,2,3,4,5,6,7,8]
Run Code Online (Sandbox Code Playgroud)
至
l2 = [(1,2),(3,4),(5,6),(7,8)]
Run Code Online (Sandbox Code Playgroud)
因为想要循环
for x,y in l2:
draw_thing(x,y)
Run Code Online (Sandbox Code Playgroud)
Nic*_*kis 10
一个好方法是:
from itertools import izip
it = iter([1, 2, 3, 4])
for x, y in izip(it, it):
print x, y
Run Code Online (Sandbox Code Playgroud)
输出:
1 2
3 4
>>>
Run Code Online (Sandbox Code Playgroud)
以尼克的回答为基础:
>>> from itertools import izip
>>> t = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> for a, b in izip(*[iter(t)]*2):
... print a, b
...
1 2
3 4
5 6
7 8
9 10
11 12
>>> for a, b, c in izip(*[iter(t)]*3):
... print a, b, c
...
1 2 3
4 5 6
7 8 9
10 11 12
>>> for a, b, c, d in izip(*[iter(t)]*4):
... print a, b, c, d
...
1 2 3 4
5 6 7 8
9 10 11 12
>>> for a, b, c, d, e, f in izip(*[iter(t)]*6):
... print a, b, c, d, e, f
...
1 2 3 4 5 6
7 8 9 10 11 12
>>>
Run Code Online (Sandbox Code Playgroud)
不太可读,但它显示了一种简洁的方式来获得你想要的任何大小元组.
| 归档时间: |
|
| 查看次数: |
322 次 |
| 最近记录: |