Python中zip的所有变体
比如,我有一段代码,看起来是这样的:
a = [1, 2]
b = [4, 5]
我该怎么才能得到像这样的结果:
[(1,4), (1,5), (2,4), (2,5)]
就像函数 zip
做的那样,不过是所有可能的组合。或者我做不到吗?
4 个回答
9
你可以用列表推导式来很方便地实现这个功能,或者如果你只是想遍历组合,使用生成器表达式会更好。
下面是用列表推导式的例子:
a = [1, 2]
b = [4, 5]
[(i, j) for i in a for j in b]
这里是用生成器表达式的例子:
for pair in ((i, j) for i in a for j in b):
print(pair)
11
如果你只关心结果,那么你需要用到 itertools.product
这个工具(感谢 @DSM 的推荐)。不过,如果你对生成这种结果的算法感兴趣,那它叫做 递归下降解析器。在这个例子中,算法的运行方式如下(为了清晰起见,我这里只打印结果):
def product(L, tmp=None):
if tmp is None:
tmp = []
if L==[]:
print tmp
else:
for i in L[0]:
product(L[1:], tmp+[i])
因此,
>>> product([[1,2], [4,5]])
[1, 4]
[1, 5]
[2, 4]
[2, 5]
希望这对你有帮助
67
你想要使用 itertools.product 这个功能:
>>> import itertools
>>> a = [1,2]
>>> b = [4,5]
>>> list(itertools.product(a,b))
[(1, 4), (1, 5), (2, 4), (2, 5)]