组合两个列表(所以[['a','b'],['c','d']] = ['ac', 'ad', 'bc', 'bd])pythonic 方式



给定一个列表列表,例如:

[['a', 'b'], ['c', 'd'], ['e']] 

结果应为:

['ace', 'ade', 'bce', 'bde']  

嵌套列表的长度将不同。必须保持顺序 - 即第一个字母必须来自第一个列表,第二个字母必须来自第二个列表,依此类推。

这是我当前的递归解决方案:

def combine_letters(l)
    if len(l) == 0: 
        return l[0]
    temp = [x + y for x in l[0] for y in l[1]] 
    new = [temp] + l[2:]
    return combine_letters(new)

但是,我觉得应该有一种快速的,甚至可能是一行的方法,可以使用reduce功能来实现。有什么想法吗?

谢谢!

编辑:这与链接的问题并不完全相似。首先,它适用于任意数量的子列表。其次,它返回字符串而不是元组。

>>> L = [['a', 'b'], ['c', 'd'], ['e']]
>>> import itertools
>>> list(itertools.product(*L))
[('a', 'c', 'e'), ('a', 'd', 'e'), ('b', 'c', 'e'), ('b', 'd', 'e')]
>>> list(''.join(tup) for tup in list(itertools.product(*L)))
['ace', 'ade', 'bce', 'bde']

最新更新