列表中列表的所有唯一组合
All unique combinations of lists within list
给出以下列表[[1, 2, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]
。如何获得包含所有子列表组合的列表的所有组合?列表中列表的顺序无关紧要。
例如,这里我们有两个:[[1, 3, 2], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]
、[[2, 1, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]
等
我偶然发现了非常相似的问题和合适的答案:
All combinations of a list of lists
How to get all possible combinations of a list’s elements?
但是 none 他们解决了这个特殊问题。
How can I get all combinations of lists that hold all the combinations of the sublists? The order of the lists in the list does not matter. E.g. [[1, 3, 2], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]], [[2, 1, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]
您需要排列所有内部列表,然后对它们进行乘积。首先将每个内部列表的排列存储在二维列表中(在代码中命名为 all_perms
),然后这些排列的乘积将是所需的答案,为了唯一性,我们需要将它们存储在 set
中。 Python的itertools.permutations
gives all permutations and itertools.product
给出了其中所有的笛卡尔积。这是代码:
from itertools import permutations as perm, product
# lists = [[1, 2, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]
lists = [[1,2],[3,4]] # let's check for a small input first
all_perms = [[] for _ in range(len(lists))]
for i, lst in enumerate(lists):
all_perms[i].extend(list(perm(lst)))
answer = set()
prods = product(*all_perms)
for tup in prods:
answer.add(tup)
print(answer)
# Output: {((1, 2), (4, 3)), ((2, 1), (3, 4)), ((2, 1), (4, 3)), ((1, 2), (3, 4))}
如有任何疑问,请随时提出。
给出以下列表[[1, 2, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]
。如何获得包含所有子列表组合的列表的所有组合?列表中列表的顺序无关紧要。
例如,这里我们有两个:[[1, 3, 2], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]
、[[2, 1, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]
等
我偶然发现了非常相似的问题和合适的答案:
All combinations of a list of lists
How to get all possible combinations of a list’s elements?
但是 none 他们解决了这个特殊问题。
How can I get all combinations of lists that hold all the combinations of the sublists? The order of the lists in the list does not matter. E.g.
[[1, 3, 2], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]], [[2, 1, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]
您需要排列所有内部列表,然后对它们进行乘积。首先将每个内部列表的排列存储在二维列表中(在代码中命名为 all_perms
),然后这些排列的乘积将是所需的答案,为了唯一性,我们需要将它们存储在 set
中。 Python的itertools.permutations
gives all permutations and itertools.product
给出了其中所有的笛卡尔积。这是代码:
from itertools import permutations as perm, product
# lists = [[1, 2, 3], [4, 2, 5, 6], [7, 2, 5], [8, 9, 10]]
lists = [[1,2],[3,4]] # let's check for a small input first
all_perms = [[] for _ in range(len(lists))]
for i, lst in enumerate(lists):
all_perms[i].extend(list(perm(lst)))
answer = set()
prods = product(*all_perms)
for tup in prods:
answer.add(tup)
print(answer)
# Output: {((1, 2), (4, 3)), ((2, 1), (3, 4)), ((2, 1), (4, 3)), ((1, 2), (3, 4))}
如有任何疑问,请随时提出。