Python - 将列表拆分为成对和唯一元素

4

我希望你能帮我翻译以下内容,这与IT技术有关。我有一个列表(比如[a,b,c,d]),我需要将它分成所有可能的方式中的一对和唯一元素(顺序不重要),即:

[a,b,c,d], [(a,b), c,d], [(a,b), (c,d)], [a, (b,c), d], [(a,d), (b, c)]...

等等看。 这个帖子 解决了只使用对的情况下的问题,但是我还需要独特的元素,而我无法做到这一点。任何想法都将不胜感激。谢谢!

4个回答

3
也许更简单的解决方案是递归的。 只需创建带有第一个元素的每个组合,并移动到没有它的子列表。
def partition(L):
    if len(L) <= 1:
        return [L]

    partitions = [[L[0]] + p for p in partition(L[1:])]
    for i in xrange(1, len(L)):
        partitions.extend([[(L[0], L[i])] + p for p in partition(L[1:i]+L[i+1:])])

    return partitions

我承认,这很简单。 - JuniorCompressor

1

给定一个函数,它可以将一个偶数长度的列表分成一对,但不考虑顺序:

def gen_only_pairs(l):
    if not l:
        yield []
        return

    for i in xrange(1, len(l)):
        l[1], l[i] = l[i], l[1]
        for v in gen_only_pairs(l[2:]):
            yield [(l[0], l[1])] + v
        l[1], l[i] = l[i], l[1]

我们可以生成我们想要的结果:
from itertools import combinations

def gen(a):
    # For all number of pairs
    for npairs in xrange(0, len(a) // 2 + 1): 
        # For each combination of 2 * npairs elements
        for c in combinations(a, 2 * npairs):
            rest = list(set(a) - set(c))
            # Generate all splits of combination into pairs
            for v in gen_only_pairs(list(c)):
                # Also add the rest of the elements
                yield v + rest

并且像这样使用:
for c in gen([1, 2, 3, 4]):
    print c

输出:

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

我会仔细研究您的答案,非常感谢。将来,我希望能够实现从[1, 2, 3, 4, 5, 6] => [(1, 2, 3), (4, 5, 6)], [(1, 2, 3), (4, 5), 6], [(1, 2, 3), 4, (5, 6)], [(1, 2, 3), (4, 6), 5)], [(1, 2, 3), 4, 6, 5)]等一系列组合的通用方法。 - Jose Ricardo Bustos M.

0

使用itertools中的组合:

from itertools import combinations

data = ['a', 'b', 'c', 'd']
pairs = [i for i in combinations(data, 2)]
>>> pairs
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

triplets = [i for i in combinations(data, 3)]
>>> triplets
[('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd')]

等等。


0

好的!让我们看看,这不是我能想到的最漂亮的代码,而且我相信我们可以从中删减一些行,但至少它是通用的(提取元组到最大大小),我想与你们分享!

from itertools import permutations

thelist = ['a', 'b', 'c', 'd']

def tuplets(l, max):
    out = []
    for i in permutations(l):
        for j in xrange(1, max + 1):
            pick(list(i), max, out, [], j, 0)
    return out

def pick(l, max, out, branch, num, idx):
    if (num == 1):
        picked = l[idx]
    else:
        picked = tuple(l[idx:idx+num])

    newBranch = list(branch)
    newBranch.append(picked)

    if idx + num == len(l):
        out.append(newBranch)
        return

    for i in xrange(1, max + 1):
        if idx + i + num > len(l):
            continue
        pick(l, max, out, newBranch, i, idx + num)

print tuplets(thelist, 2)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接