[英]How do you make value pairs and repeat them?
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
This is what I have so far and I know the output is: 到目前为止,这是我所知道的,输出是:
(['b', 'c'], ['e', 'f'])
I want it to return: 我希望它返回:
{'a': ['b', 'b', 'c', 'c'], 'd': ['e', 'f', 'e', 'f']}
I can try to return the dictionary myself -- but in the list -- how do you make pairs and repeat them? 我可以尝试自己返回字典-但在列表中-您如何配对并重复配对?
Use itertools.product()
to produce pairs, which you can then append to your output: 使用
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
or you can nest the loops: 或者您可以嵌套循环:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.