【问题标题】:Include permutations of nested lists包括嵌套列表的排列
【发布时间】:2021-10-24 23:20:56
【问题描述】:

我有以下函数来获取列表的排列数(不重复元素):

import itertools

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

只要我提供的列表不包含嵌套列表,这对我来说就很好。 Itertools 将嵌套元素视为一个完整的元素,并且不会费心生成包含不同顺序嵌套列表的排列。

如果我运行permutations_without_repetition([[1, 2], 3], 2),我得到的唯一结果是:

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

我知道这是预期的行为,但我希望结果是:

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

返回包含嵌套列表排列的排列以产生上述结果的最简单方法是什么?

【问题讨论】:

    标签: python python-3.x list nested permutation


    【解决方案1】:

    您可以使用递归生成器函数:

    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])))
    

    输出:

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

    使用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])))
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      相关资源
      最近更新 更多