【问题标题】:I m looking to generate combination of Lists of List in python [closed]我正在寻找在python中生成列表列表的组合[关闭]
【发布时间】:2020-10-05 07:48:39
【问题描述】:

假设

L=[1,2,3...8]

我需要的是这个

   [
[[1,2,3,5],[4,6,7,8]] , 
[[1 2 4 7] [3,5,6,8]] ,
..... ]

列表中元素的数量应该取决于用户并且列表是不相交的。我真的不知道如何在 python 中做到这一点

【问题讨论】:

标签: python list combinations itertools


【解决方案1】:

IIUC 获取rangepermutations 并在每次迭代时将列表分成两个块:

from itertools import permutations

l = range(1,9)
n = len(l)//2

[[[*r[:n]],[*r[n:]]] for r in permutations(l)]
[[[1, 2, 3, 4], [5, 6, 7, 8]],
 [[1, 2, 3, 4], [5, 6, 8, 7]],
 [[1, 2, 3, 4], [5, 7, 6, 8]],
 [[1, 2, 3, 4], [5, 7, 8, 6]],
 [[1, 2, 3, 4], [5, 8, 6, 7]],
 [[1, 2, 3, 4], [5, 8, 7, 6]],
 ...

要拆分成任意大小的块(比如4),您可以使用嵌套列表推导。请记住,对于更大的尺寸,您最终会得到大量的排列。您可以使用生成器,然后使用itertools.islice 获取第一个n

from itertools import islice

l = range(1,25)
n = len(l)
s = n//4
list(islice(([r[i:i+s] for i in range(0,n,s)] for r in permutations(l)), 5))
[[(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, 2, 3, 4, 5, 6),
  (7, 8, 9, 10, 11, 12),
  (13, 14, 15, 16, 17, 18),
  (19, 20, 21, 22, 24, 23)],
 [(1, 2, 3, 4, 5, 6),
  (7, 8, 9, 10, 11, 12),
  (13, 14, 15, 16, 17, 18),
  (19, 20, 21, 23, 22, 24)],
 ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多