简体   繁体   English

包括嵌套列表的排列

[英]Include permutations of nested lists

I have the following function to get the number of permutations (without repeating elements) of a list:我有以下函数来获取列表的排列数(没有重复元素):

import itertools

def permutations_without_repetition(samples, size):
    return len(list(itertools.permutations(samples, size)))

Which works fine for me as long as the list I provide doesn't contain nested lists.只要我提供的列表不包含嵌套列表,这对我来说就很好用。 Itertools treats nested elements just as one whole element, and doesn't bother also generating permutations containing differently-ordered nested lists. Itertools 将嵌套元素视为一个完整的元素,并且不会打扰生成包含不同顺序嵌套列表的排列。

If I run permutations_without_repetition([[1, 2], 3], 2) , the only results I get are:如果我运行permutations_without_repetition([[1, 2], 3], 2) ,我得到的唯一结果是:

[([1, 2], 3), (3, [1, 2])]

I know this is the expected behaviour, but I would like the result to be:我知道这是预期的行为,但我希望结果是:

[([1, 2], 3), (3, [1, 2]), ([2, 1], 3), (3, [2, 1])]

What's the easiest way to also return permutations that contain permutations of nested lists, to produce the result above?返回包含嵌套列表排列的排列以产生上述结果的最简单方法是什么?

You can use a recursive generator function:您可以使用递归生成器函数:

def combos(d, c = []):
   if not isinstance(d, list):
      yield d
   elif not d:
      yield c
   else:
      for i, a in enumerate(d):
         for k in combos(a, c = []):
             yield from combos(d[:i]+d[i+1:], c+[k])

print(list(combos([[1, 2], 3])))

Output:输出:

[[[1, 2], 3], [[2, 1], 3], [3, [1, 2]], [3, [2, 1]]]

Shorter solution using itertools :使用itertools更短的解决方案:

import itertools as it
def combos(d):
   if not isinstance(d, list):
      yield d
   else:
      for i in it.permutations(d):
         yield from map(list, it.product(*[combos(j) for j in i]))

print(list(combos([[1, 2], 3])))

Output:输出:

[[[1, 2], 3], [[2, 1], 3], [3, [1, 2]], [3, [2, 1]]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM