我在理解我的问题时遇到了很多麻烦:
我有2个名单:
from = ['A', 'B', 'C']
to = ['D', 'E', 'F']
我需要生成一个矩阵,将一个列表中的每个项目组合到另一个列表中:
final = [[['A', 'D'], ['B', 'E'], ['C', 'F']],
[['A', 'D'], ['B', 'F'], ['C', 'E']],
[['A', 'E'], ['B', 'F'], ['C', 'D']],
[['A', 'E'], ['B', 'D'], ['C', 'F']],
[['A', 'F'], ['B', 'D'], ['C', 'E']],
[['A', 'F'], ['B', 'E'], ['C', 'D']]]
我试图这样做:
for i in range(len(initial)):
for j in range(len(transformed)):
self.semantic_networks[j][i][0] = self.initial_figure[i]['name']
self.semantic_networks[i][j][1] = self.transformed_figure[(j + i) % len(self.transformed_figure)]['name']
但是,我只获得了最高分:
[['A', 'D'], ['B', 'E'], ['C', 'F']]
[['A', 'E'], ['B', 'F'], ['C', 'D']]
[['A', 'F'], ['B', 'D'], ['C', 'E']]
[[0, 0], [0, 0], [0, 0]]
[[0, 0], [0, 0], [0, 0]]
[[0, 0], [0, 0], [0, 0]]
我想要得到什么?组合?排列?组合的组合??
任何提示???
答案 0 :(得分:4)
在第二个列表中应用itertools.permutations
,然后使用第一个列表zip
每个排列。
from itertools import permutations
lst1 = ['A', 'B', 'C']
lst2 = ['D', 'E', 'F']
for p in permutations(lst2):
print zip(lst1, p)
#
[('A', 'D'), ('B', 'E'), ('C', 'F')]
[('A', 'D'), ('B', 'F'), ('C', 'E')]
[('A', 'E'), ('B', 'D'), ('C', 'F')]
[('A', 'E'), ('B', 'F'), ('C', 'D')]
[('A', 'F'), ('B', 'D'), ('C', 'E')]
[('A', 'F'), ('B', 'E'), ('C', 'D')]
答案 1 :(得分:-1)
似乎你想要所有可能的排列组合:
import itertools
a = ['A', 'B', 'C']
b = ['D', 'E', 'F']
items = zip(itertools.permutations(a), itertools.permutations(b))