udo*_*984 3 python list python-3.x
如果我有一个列表列表,并且想要从每个不同的索引中找到所有可能的组合,我该怎么做?
例如:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)
我想找到
all_possibility = [[1, 5, 9], [1, 8, 6], [4, 2, 9], [4, 8, 3], [7, 2, 6], [7, 5, 3]]
Run Code Online (Sandbox Code Playgroud)
在哪里
[1,5,9]:1是[1,2,3]的第1个元素,5是[4,5,6]的第2个元素,9是[7,8,9]的第3个元素。
[1,8,6]:1是[1,2,3]的第1个元素,8是[7,8,9]的第2个元素,6是[4,5,6]的第3个元素。
等等。
(已编辑)注意:我希望结果与列表的原始元素具有相同的顺序。[1, 8, 6] 但不是 [1, 6, 8],因为 8 是 [7, 8, 9] 的第二个元素。
您正在寻找的是 Python 中的笛卡尔积itertools.product:
>>> import itertools
>>> list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> all_possibility = list(itertools.product(*list_of_lists))
>>> print(all_possibility)
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 6, 7), (1, 6, 8),
(1, 6, 9), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 6, 7),
(2, 6, 8), (2, 6, 9), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 5, 7), (3, 5, 8), (3, 5, 9),
(3, 6, 7), (3, 6, 8), (3, 6, 9)]
Run Code Online (Sandbox Code Playgroud)
如果您想要基于索引而不是值的排列,您可以使用itertools.combinations来获取可能的索引,然后使用这些索引从子列表中获取相应的值,如下所示:
>>> list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> length = 3
>>> all_indices = list(itertools.permutations(range(length), length))
>>> all_possibility = [[l[i] for l,i in zip(list_of_lists, indices)] for indices in all_indices]
>>> print(all_possibility)
[[1, 5, 9], [1, 6, 8], [2, 4, 9], [2, 6, 7], [3, 4, 8], [3, 5, 7]]
Run Code Online (Sandbox Code Playgroud)