简体   繁体   English

将列表分成两个非空列表的所有方法

[英]All ways of partitioning a list into two non-empty lists

[0.0, 1.0, 2.0, 3.0, 4.0] [0.0,1.0,2.0,3.0,4.0]

I have 5 numbers and two groups, left and right. 我有5个数字和两个组,左右。 Each number has two choices - it can go left or right. 每个号码有两个选择 - 它可以向左或向右。 I need a list that contains all partitioning of the list [0,1,2,3,4] into two non empty parts. 我需要一个列表,其中包含列表[0,1,2,3,4]的所有分区为两个非空部分。 For example: [([0], [1,2,3,4]), ([0,1], [2,3,4]), ...,] 例如:[([0],[1,2,3,4]),([0,1],[2,3,4]),...,]

Note that there are a total of (2^5 -2)/2 partitioning - order doesn't matter and I don't want repeats. 请注意,总共有(2 ^ 5 -2)/ 2分区 - 顺序无关紧要,我不想重复。 Meaning I don't want something like this (if my list was [1,2,3,4]): 意思是我想要这样的东西(如果我的列表是[1,2,3,4]):

[] [1, 2, 3, 4]
[1] [2, 3, 4]
[2] [1, 3, 4]
[1, 2] [3, 4]
[3] [1, 2, 4]
[1, 3] [2, 4]
[2, 3] [1, 4]
[1, 2, 3] [4]
[4] [1, 2, 3]
[1, 4] [2, 3]
[2, 4] [1, 3]
[1, 2, 4] [3]
[3, 4] [1, 2]
[1, 3, 4] [2]
[2, 3, 4] [1]
[1, 2, 3, 4] []

I've looked into all of the itertools functions and none seem to work. 我查看了所有的itertools函数,但似乎都没有。


Edit: for list [i for i in range(16)], which has 16 elements, If I do the following, this is what I see: 编辑:对于列表[i for i in range(16)],它有16个元素,如果我执行以下操作,这就是我所看到的:

 n = len(l)//2 + 1
>>> xs = list(chain(*[combinations(l, i) for i in range(1, n)]))
>>> pairs = [(list(x), list(set(l) - set(x))) for x in xs]
>>> print len(pairs)
    39202
>>> (2**16-2)/2
    32767

In fact, it doesn't work for a list with 6 elements either. 实际上,它对于包含6个元素的列表也不起作用。 I don't see why... 我不明白为什么......

The problem occurs for all even length lists. 所有偶数长度列表都会出现问题。 For example, when I try a length 2 list, I get: 例如,当我尝试长度2列表时,我得到:

[([0.0], [1.0]), ([1.0], [0.0])] [([0.0],[1.0]),([1.0],[0.0])]

The stuff is there in itertools , maybe you just weren't looking in the right places. 这些东西在itertools ,也许你只是没有找到正确的地方。

Here is teh codez: 这是代码:

from collections import OrderedDict
from itertools import chain, combinations

def partition(L):
    n = len(L)//2 + 1
    xs = chain(*[combinations(L, i) for i in range(1, n)])
    pairs = (tuple(sorted([x, tuple(set(L) - set(x))])) for x in xs)
    return OrderedDict.fromkeys(pairs).keys()

Output: 输出:

>>> for pair in partition([1,2,3,4]):
...     left, right = map(list, sorted(pair, key=len))
...     print left, right
...
[1] [2, 3, 4]
[2] [1, 3, 4]
[3] [1, 2, 4]
[4] [1, 2, 3]
[1, 2] [3, 4]
[1, 3] [2, 4]
[1, 4] [2, 3]

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

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