繁体   English   中英

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

[英]merge two sets with considering the order of each one (in Python)

我有两个变量i,j它们显示两个集合1和2的长度,如len(one)= i和len(two)= j。 现在,我想合并这两个集合,以便具有每个集合的有序排列。 我还需要在Python中索引每个新集。

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

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

itertools借用partition配方:

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

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

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的顺序。 此处给出的示例假定您的输入和输出是列表。

暂无
暂无

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

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