动态确定我的意思是在运行时未知.
这是一个字典:
aDict[1]=[1,2,3]
aDict[2]=[7,8,9,10]
aDict[n]=[x,y]
Run Code Online (Sandbox Code Playgroud)
我不知道会有多少n但是我想循环如下:
for l1 in aDict[1]:
for l2 in aDict[2]:
for ln in aDict[n]:
# do stuff with l1, l2, ln combination.
Run Code Online (Sandbox Code Playgroud)
有关如何做到这一点的任何建议?我对python比较新,所以请保持温和(虽然我在php中编程).顺便说一下,我使用的是python 3.1
DrT*_*rsa 11
from itertools import product
for vals in product(*list(aDict.values())):
# vals will be (l1, l2, ..., ln) tuple
Run Code Online (Sandbox Code Playgroud)
Mat*_*euW 11
与DrTyrsa相同的想法,但确保顺序是正确的.
from itertools import product
for vals in product( *[aDict[i] for i in sorted(aDict.keys())]):
print vals
Run Code Online (Sandbox Code Playgroud)