你如何制作价值对并重复它们?

时间:2013-11-22 22:36:28

标签: python dictionary

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']}

我可以尝试自己返回字典 - 但在列表中 - 你如何制作并重复它们?

1 个答案:

答案 0 :(得分: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