2017-04-03 31 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