以pythonic方式组合两个列表

时间:2015-01-01 13:55:08

标签: python list combinations itertools

我不知道如何搜索这个,但是,我无法找到一个明显的解决方案来解决我的pythonic问题。我想结合两个列表(一个是另一个被操纵的列表)并通过保持列表长度不变来置换它们。

一个例子:

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

combined = [['a','B','C','D'], ['A','b','C','D'], ..., ['a','b','c','d']]

然后我可以使用itertools来置换它们。但是,第一步对我来说不容易管理。我不想要嵌套的for循环和Co。

1 个答案:

答案 0 :(得分:7)

使用zipitertools.productlist comprehension

>>> import itertools
>>> a = ['A','B','C','D']
>>> b = ['a','b','c','d']  # [x.lower() for x in a]
>>> [list(x) for x in itertools.product(*zip(a, b))]
[['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'd'], ['A', 'B', 'c', 'D'],
 ['A', 'B', 'c', 'd'], ['A', 'b', 'C', 'D'], ['A', 'b', 'C', 'd'],
 ['A', 'b', 'c', 'D'], ['A', 'b', 'c', 'd'], ['a', 'B', 'C', 'D'],
 ['a', 'B', 'C', 'd'], ['a', 'B', 'c', 'D'], ['a', 'B', 'c', 'd'],
 ['a', 'b', 'C', 'D'], ['a', 'b', 'C', 'd'], ['a', 'b', 'c', 'D'],
 ['a', 'b', 'c', 'd']]