梳理循环

时间:2016-12-06 02:56:35

标签: python

当展开for循环时,你会做这样的事情:

for a, b, c in itertools.product(x1, x2, x3):
    ...

但是,如何处理其中一个元素作为参数来检索也要遍历的列表的情况?例如:

for a, b in itertools.product(x1, get_b_elements(a)):
    ...

这甚至可能吗?

2 个答案:

答案 0 :(得分:0)

for a in x1:
    for b in get_b_elements(a):
       #do something with (a, b)

仅列出备选方案:

for (a, b) in [(a_i, b_i) for a_i in x1 for b_i in get_b_elements(a_i)]:
    #do something with (a, b)

正如@wim指出的那样,这些"平坦的"你想要的循环。

答案 1 :(得分:-1)

试试这个:

alphabets = [a,b,c,d]
xs = [x1,x2,x3]

itertools.product(alphabets, xs)
相关问题