2017-04-03 85 views
0

我正在尝试做一个迭代,但有一些修复参数,并且可迭代参数在列表中。 这是我要找的输出:带有修复参数的Python itertools

(fix1, fix2, fix3, [iterable1_1, iterable2_1, iterable3_1], fix4) 

(fix1, fix2, fix3, [iterable1_1, iterable2_1, iterable3_2], fix4) 

等,基本上只有三一的名单内的变化;其余的不变。

到目前为止,我已经尝试过这一点,但它并没有真正起作用。

iterable = itertools.product([fix1], [fix2], [fix3], [[iter1_1, iter1_2, iter1_3], [iter2_1, iter2_2], [iter3_1, iter3_2, iter3_3]], [fix4]) 

iter1,iter2和iter3有不同的长度,但我不认为这是相关的。我有两个列表,a = [1,2]和b = [3,4],以及一些固定参数f1 = 10,f2 = 20,f3 = 30 期望的输出为:

(10, 20, [1,3], 30) 
(10, 20, [1,4], 30) 
(10, 20, [2,3], 30) 
(10, 20, [2,4], 30) 
+1

您的问题仍然模棱两可。请编辑您的原始帖子以包含示例输入和输出 – inspectorG4dget

回答

2

这听起来像你想要的东西,如:

result = [(fix1, fix2, fix3, [a, b, c], fix4) 
      for a, b, c in itertools.product(iterable1, iterable2, iterable3)] 

如果与a, b, c内序列可以是一个元组,而不是一个清单,你就不需要拆包:

result = [(fix1, fix2, fix3, prod, fix4) for prod in product(...)] 
0

如果有疑问,请创建一个函数。

def framed(*iters): 
    for pair in itertools.product(*iters): 
     yield (10, 20, pair, 30) 

for result in framed([1, 2], [3, 4]): 
    print result 

(10, 20, (1, 3), 30) 
(10, 20, (1, 4), 30) 
(10, 20, (2, 3), 30) 
(10, 20, (2, 4), 30) 
1
import itertools 
a = [1,2] 
b = [3,4] 
f1 = 10 
f2 = 20 
f3 = 30 

获取产品ab

things = itertools.product(a,b) 

使用固定值和产品

z = [(f1, f2, thing, f3) for thing in map(list, things)] 


>>> for thing in z: 
    print thing 

(10, 20, [1, 3], 30) 
(10, 20, [1, 4], 30) 
(10, 20, [2, 3], 30) 
(10, 20, [2, 4], 30) 
>>> 

这不是普通的,它不会处理的固定的东西迭代事情的任意数量的构建结果

这里是一个更通用的解决方案

def f(fixed, iterables): 
    things = itertools.product(*iterables) 
    last = fixed[-1] 
    for thing in things: 
     out = fixed[:-1] 
     out.extend((thing, last)) 
     yield out 

用法:

for thing in f([f1, f2, f3, f4], [a, b]): 
    print thing