以子列表的形式获取列表的所有可能组合 [英] getting all possible combinations of a list in a form of sublists

查看:69
本文介绍了以子列表的形式获取列表的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wonder if someone can help with the following task: What is the way to get all combinations a list can be split into sublists, when order does not matter?

假设我有4个项目的列表:

Let's say I have a list of 4 items:

import itertools as it

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

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

That will give me a list of 6 possible pairs:

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

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

How to make (out of it? or any other way) a set of lists that contain original [1, 2, 3, 4] sequence in any order? So for this example it will contain three sublists:

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

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

UPDATE: A small clarification: In other words, I need to get all sets of n-tuples such that their members contain all the population of original list, when the order within an n-tuple does not matter. Thus [(1, 2), (3, 4)] is ok, but [(2, 1), (3, 4)] is not needed because it is the same as the first set, if we ignore the order.

UPDATE2:
长度为6的列表,对于大小为2的块,此 fun 函数应如下所示:

UPDATE2: So for the list of length 6, and for chunks of size 2 this fun function should work as follows:

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 组合,并带有相反的组合,并且仅取前一半

Just zip the combinations, with its reverse and take only the first half of the resulting list

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

这篇关于以子列表的形式获取列表的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆