Python中所有可能的zip变体

ale*_*sel 23 python list

例如,我有一个代码如下:

a = [1, 2]
b = [4, 5]
Run Code Online (Sandbox Code Playgroud)

我怎么能得到这样的东西:

[(1,4), (1,5), (2,4), (2,5)]
Run Code Online (Sandbox Code Playgroud)

像函数zip一样,但具有所有可能的变体.或者不是吗?

DSM*_*DSM 39

你想要itertools.product:

>>> import itertools
>>> a = [1,2]
>>> b = [4,5]
>>> list(itertools.product(a,b))
[(1, 4), (1, 5), (2, 4), (2, 5)]
Run Code Online (Sandbox Code Playgroud)


ins*_*get 9

如果您只对结果感兴趣,那么itertools.product就是您所需要的(@DSM为+1).但是,如果您对生成此类内容的算法感兴趣,则称为递归下降.在这种情况下,算法将按如下方式运行(为了清楚起见,我将在此处打印结果):

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])
Run Code Online (Sandbox Code Playgroud)

从而,

>>> product([[1,2], [4,5]])
[1, 4]
[1, 5]
[2, 4]
[2, 5]
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助


小智 6

你可以很好地使用列表理解,或者更好地使用生成器表达式,如果你只需要迭代组合.

这是使用列表理解:

a = [1, 2]
b = [4, 5]

[(i, j) for i in a for j in b]
Run Code Online (Sandbox Code Playgroud)

这里有一个生成器表达式:

for pair in ((i, j) for i in a for j in b):
    print(pair)
Run Code Online (Sandbox Code Playgroud)


end*_*ith 5

不要忽视显而易见的事情:

out = []
for a in [1, 2]:
    for b in [4, 5]:
        out.append((a, b))
Run Code Online (Sandbox Code Playgroud)

或列出理解:

a = [1, 2]
b = [4, 5]
out = [(x, y) for x in a for y in b]
Run Code Online (Sandbox Code Playgroud)

两者都产生out == [(1, 4), (1, 5), (2, 4), (2, 5)]