2013-04-17 21 views
-2

剛開始嘗試我的手在Python和需要一些指針。清單出來二元組合和映射到數據

我期待基於某些參數的組合。

基本上,

parm1 = ['X1','X2'] 
parm2 = ['Y1','Y2'] 

我想什麼從這個得到的是

['X1','Y1','X1','Y1'] 
['X1','Y1','X1','Y2'] 
['X1','Y1','X2','Y1'] 
['X1','Y1','X2','Y2'] 

我想一個可以使用二進制列表(itertools.product( 「01」,重複= 4 ))並替換每個元素,即。

0 0 0 0 
0 0 0 1 

將代表

X1 Y1 X1 Y1 
X1 Y1 X1 Y2 

什麼是這樣做的最佳方法是什麼?

編輯:讓我來添加更多的信息。

Colour = ['Black','White'] 
Type = ['Car','Bike'] 

所以,我想這種格式分爲以下

     ('Colour','Type','Colour','Type') 
('0', '0', '0', '0')-->('Black','Car','Black','Car') 
('0', '0', '0', '1')-->('Black','Car','Black','Bike') 
('0', '0', '1', '0')-->('Black','Car','White','Car') 
('0', '0', '1', '1')-->('Black','Car','White','Bike') 
('0', '1', '0', '0') 
('0', '1', '0', '1') 
('0', '1', '1', '0') 
('0', '1', '1', '1') 
('1', '0', '0', '0') 
('1', '0', '0', '1') 
('1', '0', '1', '0') 
('1', '0', '1', '1') 
('1', '1', '0', '0') 
('1', '1', '0', '1') 
('1', '1', '1', '0') 
('1', '1', '1', '1')-->('White','Bike','White','Bike') 

我知道這可以用一個if語句來完成對列表中的每個指標,但是否有其他方法?

再次編輯:

我寫了這一點,但覺得有多大是一個更好的解決方案?

import itertools 
q=[] 
x=["","","",""] 
q=list(itertools.product("01", repeat=4)) 
for p in q: 
    if float(p[0]) == 0: 
     x[0]= "Black" 
    else: 
     x[0] = "White" 
    if float(p[1]) == 0: 
     x[1]= "Car" 
    else: 
     x[1] = "Bike" 
    if float(p[2]) == 0: 
     x[2]= "Black" 
    else: 
     x[2] = "White" 
    if float (p[3]) == 0: 
     x[3] = "Car" 
    else: 
     x[3] = "Bike" 
    print p 
    print x 
+1

是否有規則選擇一些組合? – perreal

+3

您能否更好地解釋一下,您如何從parm1和parm2獲得您要求的輸出列表? – mgilson

+2

您列出的名單'給出的四個(itertools.product(PARM1,parm2,PARM1,parm2))[4]',但我不知道,如果你只列出的前四個你想要的,只是沒不要提你想要更多,或者如果這些只是你想要的四個,我不理解選擇規則。 – DSM

回答

2

基本上你想要的就是一個平坦的版本:

from itertools import product 
nested = product(product(Colour, Type), repeat=2) 
print list(nested) 
# [(('Black', 'Car'), ('Black', 'Car')), 
# (('Black', 'Car'), ('Black', 'Bike')), 
# ... 
# ] 

所以在這裏你去:

from itertools import product 
nested = product(product(Colour, Type), repeat=2) 

# flatten it by unpacking each element 
print [(a,b,c,d) for ((a,b),(c,d)) in nested] 

# alternative way to flatten the product 
from itertools import chain 
print [tuple(chain.from_iterable(x)) for x in nested] 

要轉換(0,1)列表中,您可以使用這些數字作爲指標:

from itertools import product 

Colour = ['Black','White'] # so Color[0] == 'Black' 
Type = ['Car','Bike'] 

#make that list 
nested = product((0,1), repeat=4) # use numbers not strings 
print [(Colour[a], Type[b], Colour[c], Type[d]) for (a,b,c,d) in nested] 
+0

我可能在嵌套的''或'chain.from_iterable'中使用'[tuple(chain(* p))';似乎很遺憾使用'repeat'來避免硬編碼,然後在最後重新引入它。 – DSM

+0

我在'嵌套=產品得到一個語法錯誤(產品(顏色,類型),重複= 2))' – Ash

+0

我傻,想通了,'itertools.product' – Ash