合并两个集合,并考虑每个集合的顺序(在Python中)

2024-04-25 12:55:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个变量I,j,它们表示两个集合1和2的长度,比如len(one)=I和len(two)=j。现在,我想合并这两个集合,使得每个集合都有有序排列。我还需要在Python中索引每个新的集合。你知道吗

例如: 一个包含第一个大写字母i,两个包含小写字母

 len(one) = i  
    len(two) = j 
expected outputs = {'abABC...', 'aAbBC...', 'aABcC...', 'aABCb...',...}

我尝试了以下代码,但它不工作。如果有人能帮助我,我将不胜感激。你知道吗

    from functools import reduce
    from itertools import combinations

    def assign(v, p):
        v[p[0]] = p[1]
        return v

    def interp(word1, word2, size):
        return (''.join(reduce(assign, zip(comb1, word1), zip(comb2, word2)))
                for comb1, comb2 in zip(combinations(range(size), len(word1)),
                                        combinations(range(size), len(word2))))

    print('\n'.join(interp("ABC", "ab", 5)))

Tags: fromimportreducesizelenreturndefzip
2条回答

可以使用一个函数,将两个列表之一的第一项与列表其余部分的组合递归合并:

def merge(a, b):
    if a and b:
        for (first, *rest), other in (a, b), (b, a):
            yield from ([first, *merged] for merged in merge(rest, other))
    elif a or b:
        yield a or b

以便:

for combination in merge(['A', 'B', 'C'], ['a', 'b']):
    print(''.join(combination))

输出:

ABCab
ABabC
ABaCb
AabBC
AaBCb
AaBbC
abABC
aABCb
aABbC
aAbBC

请注意,在Python中,集合是无序的,因此,如果输入是集合,则无法按照预期输出的建议保持ABCab的顺序。这里给出的示例假设您的输入和输出是列表。你知道吗

借用itertools^{}配方:

one = set(['A', 'B', 'C'])
two = set(['a', 'b'])

from itertools import permutations, tee, filterfalse, chain

def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10))  > 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

iter_1 = ((i, 1) for i in one)
iter_2 = ((i, 2) for i in two)

for c in permutations(chain(iter_1, iter_2), 5):
    p1, p2 = map(list, partition(lambda k: k[1] == 1, c))
    if sorted(p1, key=lambda k: k[0]) == p1 and sorted(p2, key=lambda k: k[0]) == p2:
        print(''.join(i[0] for i in c))

印刷品:

ABCab
ABaCb
ABabC
AaBCb
AaBbC
AabBC
aABCb
aABbC
aAbBC
abABC

相关问题 更多 >