我有以下格式
的表格{str:list of str}
table1 = {key1:['1','2','3'], key2: ['3','4','5']}
table2 = {key3:['6','7','8','9'], key4:['9','10','11','12']}
现在我需要在不使用itertools或sql命令的情况下获得两者的笛卡尔积。
我基本上需要新表:
new_table = {key1:['1','1','1','1','2','2','2','2','3','3','3','3'],
key2: ['3','3','3','3','4','4','4','4','5','5','5','5'],
key3: ['6','7','8','9','6','7','8','9'],
key4: ['9','10','11','12','9','10','11','12']}
我该怎么做?
答案 0 :(得分:5)
table1 = {"key1":['1','2','3'], "key2": ['3','4','5']}
table2 = {"key3":['6','7','8','9'], "key4":['9','10','11','12']}
n1, n2 = 4, 2
r1 = {k:[i for i in v for j in range(n1)] for k, v in table1.items()}
r2 = {k:v * n2 for k, v in table2.items()}
r1.update(r2)
print r1
<强>输出强>
{'key3': ['6', '7', '8', '9', '6', '7', '8', '9'], 'key2': ['3', '3', '3', '3', '4', '4', '4', '4', '5', '5', '5', '5'], 'key1': ['1', '1', '1', '1', '2', '2', '2', '2', '3', '3', '3', '3'], 'key4': ['9', '10', '11', '12', '9', '10', '11', '12']}
答案 1 :(得分:3)
我有一个更简单的解决方案:
new_table = {'key1': ['1','1','1','1','2','2','2','2','3','3','3','3'],
'key2': ['3','3','3','3','4','4','4','4','5','5','5','5'],
'key3': ['6','7','8','9','6','7','8','9'],
'key4': ['9','10','11','12','9','10','11','12']}
这可以为您提供您想要的内容,而不需要itertools
或甚至只是尝试解释为什么这是您想要的结果; - )