Python:从顺序不变的2个列表中创建可能的子列表

2024-10-02 16:26:55 发布

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

我有两个列表,我需要创建不同的子列表,在这些子列表中不应该再次使用顺序(请参阅示例以获取清晰的信息)

list1= [ a, b, c, d]
list2= [A, B, C, D]

我需要所有可能的子列表

[a, B,C,D], [ a,b, C, D], [A,B,c,d], [a,b,c,D] ...有2个POW4=16个解决方案[正在寻找2个POWn解决方案]

提前谢谢你


Tags: 信息示例列表顺序请参阅解决方案list2list1
3条回答

递归是你的朋友:

def sublists(l1, l2):
    if not l1:
        return [l1]
    sl = sublists(l1[1:], l2[1:])
    return [l1[:1] + l for l in sl] + [l2[:1] + l for l in sl]

或者,如果你喜欢发电机:

^{pr2}$

我有种感觉可以做得更好,但这至少可以:

from itertools import product
a = "abcd"
A = "ABCD"
print [[a[y] if x[y] else A[y] for y in range(len(x))] \
    for x in product(range(2), repeat=4)]

编辑:另一种方法:

^{pr2}$

编辑2:任意数量列表的通用解决方案:

def sublist(*lists):
    if not len(set(len(x) for x in lists)) == 1:
        raise ValueError("Lists must all be the same length")
    length = len(lists[0])
    return [[lists[y][i] for i, y in enumerate(x)] \
        for x in product(range(len(lists)), repeat=length)]

print sublist("ab", "AB", "12")
# [['a', 'b'], ['a', 'B'], ['a', '2'], ['A', 'b'], ['A', 'B'], ['A', '2'], ['1', 'b'], ['1', 'B'], ['1', '2']]
list1 = ['a', 'b', 'c', 'd']
list2 = ['A', 'B', 'C', 'D']

for i in xrange(2**len(list1)):
    output = []
    for j in xrange(0, len(list1)):
        bit = i & (1 << j)
        if bit == 0:
            output.append(list1[j])
        else:
            output.append(list2[j])
    print output

相关问题 更多 >