繁体   English   中英

以子列表的形式获取列表的所有可能组合

[英]getting all possible combinations of a list in a form of sublists

我想知道是否有人可以帮助执行以下任务:当顺序无关紧要时,将列表分成多个子列表的所有组合的方式是什么?

假设我有4个项目的清单:

import itertools as it

a = [1, 2, 3, 4]
print(list(it.combinations(a, 2)))

这将给我列出6对可能的对:

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

如何(以其他方式或其他方式)制作一组以任何顺序包含原始[1, 2, 3, 4]序列的列表? 因此,对于此示例,它将包含三个子列表:

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

更新:一个小澄清:换句话说,当一个n元组中的顺序无关紧要时,我需要获取所有n元组集,以便其成员包含所有原始列表。 因此, [(1, 2), (3, 4)]可以,但是不需要[(2, 1), (3, 4)] ,因为它与第一个集合相同,如果我们忽略其顺序。

UPDATE2:因此,对于长度为6的列表以及大小为2的块,此fun函数应如下工作:

import itertools as it
a = [1, 2, 3, 4, 5, 6,]
r = 2

# fun(a,r):
# OUT:
# [
#    (1, 2), (3, 4), (5, 6)
#    (1, 3), (2, 4), (5, 6),
#    (1, 4), (2, 3), (5, 6),
#    (1, 5), (2, 3), (4, 6),
#    (1, 6), (2, 3), (4, 5),
#  ]

只需zip组合及其反向即可,仅获取结果列表的前半部分

>>> import itertools as it
>>> lst = [1, 2, 3, 4]
>>> r = len(lst)//2
>>> combs = list(it.combinations(lst, r))
>>> list(it.islice(zip(combs, reversed(combs)), len(combs)//2))
[((1, 2), (3, 4)), ((1, 3), (2, 4)), ((1, 4), (2, 3))]

当你需要的是什么“余数” a ,你可以使用set差异

In [901]: [(c, tuple(set(a) - set(c))) for c in it.combinations(a, 2)]
Out[901]:
[((1, 2), (3, 4)),
 ((1, 3), (2, 4)),
 ((1, 4), (2, 3)),
 ((2, 3), (1, 4)),
 ((2, 4), (1, 3)),
 ((3, 4), (1, 2))]

但是,这给您的结果是所需结果的两倍,因此要消除这些重复项,我们需要对结果集进行排序和set ,这将给我们提供一组不能转换为setlist 然后,您应该将list s转换为tuple s。

In [900]: {tuple(sorted((c, tuple(set(a) - set(c))))) for c in it.combinations(a, 2)}
Out[900]: {((1, 2), (3, 4)), ((1, 3), (2, 4)), ((1, 4), (2, 3))}

如果您需要tuple listlist ,则可以使用以下内容

In [902]: s = {tuple(sorted((c, tuple(set_a - set(c))))) for c in it.combinations(a, 2)}

In [903]: [list(l) for l in s]
Out[903]: [[(1, 3), (2, 4)], [(1, 4), (2, 3)], [(1, 2), (3, 4)]]
a = [1, 2, 3, 4]
choices = []
for i in range(len(a)):
  for j in range(i+1, len(a)):
      sub_a1 = (a[i], a[j])
      sub_a2 = tuple(j for j in a if j not in sub_a1)
      sub_a = sorted([sub_a1, sub_a2])
      if sub_a not in choices:
         choices.append(sub_a)
for k in choices:
  print(k)

可能这段代码可以帮助您满足要求。

暂无
暂无

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

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