【问题标题】:How to generate all the possible permutations based on a quota?如何根据配额生成所有可能的排列?
【发布时间】:2021-05-05 18:55:38
【问题描述】:

给定两个列表 XY

X = ['A', 'B', 'C', 'D']

Y = ['I', 'J', 'K', 'L', 'M', 'N']

如何创建所有可能的 4 个组合的集合,并限制考虑至少 2 个元素 XY。例如,有效的组合如下所示:

[('A', 'J', 'M', 'D'), ..., ('I', 'M', 'B', 'C')]

原因是它包含来自XY 的2 个元素。 [('A', 'B', 'M', 'D')] 的组合无效,因为它包含来自 X 的 3 个元素和来自 Y 的 1 个元素。到目前为止,我尝试:

import itertools
set(list(itertools.permutations([e for e in zip(X, Y)])))

但是,这违反了配额限制。实现配额排列的正确方法是什么?

【问题讨论】:

    标签: python combinations permutation itertools


    【解决方案1】:

    您只需对每个列表中的 2 进行排列并组合它们,然后对每组 4 进行所有组合:

    from itertools import permutations, combinations
    X = ['A', 'B', 'C', 'D']
    Y = ['I', 'J', 'K', 'L', 'M', 'N']
    
    x = (n+m for n in permutations(X,2) for m in permutations(Y,2))
    for i in x:
        print(list(combinations(i,4)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 2012-05-05
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 2014-10-22
      • 1970-01-01
      相关资源
      最近更新 更多