【问题标题】:Python Permutation with multiple conditions (permuting 24 items in 4 groups)具有多个条件的 Python 排列(排列 4 组中的 24 个项目)
【发布时间】:2020-09-24 02:50:34
【问题描述】:

我很难弄清楚如何置换以下数据集 (data table):

它包含 24 个项目,每个项目属于 6 个项目的 4 个组之一。这些组是两个条件组合的结果,这两个条件在这里可能无关紧要。我想以某种方式排列相对于它们的组的项目,每个排列只有每个组中的一个项目。

生成的排列如下所示:

1,7,13,19

1,7,13,20

1,7,13,21

...

6,12,18,23

6,12,18,24

等等

我已经尝试过 itertools,我能够置换 24 个项目或 4 个组,但我不知道如何置换 24 个项目相对于他们的组。

【问题讨论】:

  • from itertools import permutations 然后permutations(iterable, num_elements)。见这里docs.python.org/2/library/itertools.html
  • 嗨,我已经尝试过 itertools,我能够置换 24 个项目或 4 个组,但我不知道如何置换 24 个项目相对于他们的组。
  • 所以您正在寻找所有不具有来自同一组的两个元素的排列?

标签: python conditional-statements combinations permutation product


【解决方案1】:

也可以从itertools.product 尝试产品,而不是前突变

from itertools import product

groups = 4
elems = 24
lst = list(range(1, elems+1))
elems_per_group = elems // groups
groups = [lst[i*elems_per_group:(i+1)*elems_per_group] for i in range(groups)]

for per in product(*groups):
    print(per)

【讨论】:

    【解决方案2】:
    group_list = [list(range(i, i + 6)) for i in range(1, 25, 6)]
    
    print(group_list)
    
    permutation_list = [
        [a, b, c, d]
        for a in group_list[0]
        for b in group_list[1]
        for c in group_list[2]
        for d in group_list[3]
    ]
    
    print(*(permutation_list[i] for i in [0, 2, -2, -1]), sep="\n\n")
    
    print("Total number of items =", len(permutation_list))
    

    输出:

    [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24]]
    [1, 7, 13, 19]
    
    [1, 7, 13, 21]
    
    [6, 12, 18, 23]
    
    [6, 12, 18, 24]
    Total number of items = 1296
    

    【讨论】:

      【解决方案3】:

      使用itertools.product

      你没有给出你是如何表示表格的。在我的示例中,我使用整数作为项目,您可以使用任何其他对象来代替整数,它仍然会为您提供所需的结果。

      >>> import itertools
      >>>
      >>> items = [[1,2],[3,4],[5,6],[7,8]]
      >>> list(itertools.product(*items))
      [(1, 3, 5, 7), (1, 3, 5, 8), (1, 3, 6, 7), (1, 3, 6, 8), (1, 4, 5, 7), (1, 4, 5, 8), (1, 4, 6, 7), (1, 4, 6, 8), (2, 3, 5, 7), (2, 3, 5, 8), (2, 3, 6, 7), (2, 3, 6, 8), (2, 4, 5, 7), (2, 4, 5, 8), (2, 4, 6, 7), (2, 4, 6, 8)]
      >>>
      >>> items = [[(1,"a"), (2,"b")], [(3,"c"),(4,"d")], [(5,"e"),(6,"f")]]
      >>> list(itertools.product(*items))
      [((1, 'a'), (3, 'c'), (5, 'e')), ((1, 'a'), (3, 'c'), (6, 'f')), ((1, 'a'), (4, 'd'), (5, 'e')), ((1, 'a'), (4, 'd'), (6, 'f')), ((2, 'b'), (3, 'c'), (5, 'e')), ((2, 'b'), (3, 'c'), (6, 'f')), ((2, 'b'), (4, 'd'), (5, 'e')), ((2, 'b'), (4, 'd'), (6, 'f'))]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多