分发嵌套列表,每个列表一次

时间:2019-06-26 23:01:15

标签: python list combinations

说我有以下列表:

raw_list = ['a', ['x', 'xx'], 'b', 'c', ['y', 'yy', 'yyy'], 'd']

我想在其中分布嵌套列表,以便从它们中仅每个元素出现在组合中,同时保持顺序:

[['a', 'x', 'b', 'c', 'y', 'd'],
 ['a', 'x', 'b', 'c', 'yy', 'd'],
 ['a', 'x', 'b', 'c', 'yyy', 'd'],
 ['a', 'xx', 'b', 'c', 'y', 'd'],
 ['a', 'xx', 'b', 'c', 'yy', 'd'],
 ['a', 'xx', 'b', 'c', 'yyy', 'd']]

我编写了以下代码来做到这一点:

from pprint import pprint
from itertools import tee

nested = [(e, raw_list .index(e)) for e in raw_list if len(e) > 1] 

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

combinations = []
raw_copy = raw_list[:]
for current, next_ in pairwise(nested):
    for x in current[0]:
        for y in next_[0]:
            raw_copy[current[1]] = x
            raw_copy[next_[1]] = y
            combinations.append(raw_copy)
            raw_copy = raw_list[:]

pprint (combinations)

完成工作。但是我想知道是否还有更多的Pythonic函数或方法可以实现相同的目标?

1 个答案:

答案 0 :(得分:2)

您可以使用itertools.product

from itertools import product
raw_list = ['a', ['x', 'xx'], 'b', 'c', ['y', 'yy', 'yyy'], 'd']
result = list(map(list, product(*[[i] if not isinstance(i, list) else i for i in raw_list])))

输出:

[['a', 'x', 'b', 'c', 'y', 'd'], 
 ['a', 'x', 'b', 'c', 'yy', 'd'], 
 ['a', 'x', 'b', 'c', 'yyy', 'd'], 
 ['a', 'xx', 'b', 'c', 'y', 'd'], 
 ['a', 'xx', 'b', 'c', 'yy', 'd'], 
 ['a', 'xx', 'b', 'c', 'yyy', 'd']]