2013-11-22 42 views
0
def cartesian_product(table1, table2): 

    '''(table, table) -> table 

    Return a table that is created by joining the tables table1 and table2. The 
    cartesian products of the two tables is a new table where each row in the first 
    table is paired with every row in the second table. Each table is supposed to 
    be a dictionary. 

    Example: 

    dict1 = {'a': ['b', 'c']} 
    dict2 = {'d': ['e', 'f']} 
    cartesian_product({'a': ['b', 'c']}, {'d': ['e', 'f']}) 
    {'a': ['b', 'b', 'c', 'c'], 'd': ['e', 'f', 'e', 'f']} 

    ''' 

    table1 = list(table1.values()) 
    table2 = list(table2.values()) 

    for object1 in table1: 
     x = object1 

     for object2 in table2: 
      y = object2 

      return x,y 

這是我到目前爲止,我知道的輸出是:你如何製作價值對並重復它們?

(['b', 'c'], ['e', 'f']) 

我想它返回:

{'a': ['b', 'b', 'c', 'c'], 'd': ['e', 'f', 'e', 'f']} 

我可以嘗試返回字典自己 - 但在列表中 - 你如何配對並重復它們?

+0

爲什麼是'[ 'E',「F ','e','f']和'['a','a','b','b']'。我沒有看到這裏的模式... – mgilson

+0

啊,我想我現在看到它;它應該是一個兩行的表格; 'b'和'e'是一對,所以是'b'和'f',然後'c'和'e'以及'c'和'f'等。 –

+0

哈哈...太棒了...我...有這個昨天的答案...和OP刪除他們的問題...現在我找不到保存的副本:) –

回答

1

使用itertools.product()生產對,然後你就可以添加到您的輸出:

from itertools import product 

def cartesian_product(table1, table2): 
    (table1_name, table1_columns), = table1.items() 
    (table2_name, table2_columns), = table2.items() 
    output = {table1_name: [], table2_name: []} 
    for cola, colb in product(table1_columns, table2_columns): 
     output[table1_name].append(cola) 
     output[table2_name].append(colb) 
    return output 

,或者你可以嵌套循環:

def cartesian_product(table1, table2): 
    (table1_name, table1_columns), = table1.items() 
    (table2_name, table2_columns), = table2.items() 
    output = {table1_name: [], table2_name: []} 
    for cola in table1_columns: 
     for colb in table2_columns: 
      output[table1_name].append(cola) 
      output[table2_name].append(colb) 
    return output 
+0

我很確定我的版本有它神奇的獨角獸...... :) –

+0

是的,對不起,我的神奇獨角獸unicode鑰匙跑掉了。 –

+0

我得到你在那裏做的,但我不會導入一個函數。你能詳細說明爲什麼你使用這個函數的輸出嗎? – user2924450

相關問題