目前我会这样做:
for x in [1,2,3]:
for y in [1,2,3]:
print x,y
Run Code Online (Sandbox Code Playgroud)
有办法做下面这样的事情,
for x,y in ([1,2,3],[1,2,3]):
print x,y
Run Code Online (Sandbox Code Playgroud)
想要缩短这种循环,这会引发"太多解压缩"异常.
eum*_*iro 18
import itertools
for x, y in itertools.product([1,2,3], [1,2,3]):
print x, y
Run Code Online (Sandbox Code Playgroud)
打印所有九对:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Run Code Online (Sandbox Code Playgroud)
更新:如果要从一个列表中选择两个变量x,y则可以使用repeat关键字(由agf提出):
import itertools
for x, y in itertools.product([1,2,3], repeat=2):
print x, y
Run Code Online (Sandbox Code Playgroud)
您可以在for循环中使用生成器表达式:
for x, y in ((a,b) for a in [1,2,3] for b in [5,6,7]):
print x, y
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18376 次 |
| 最近记录: |