All possible variants of zip in Python

前端 未结 4 643
渐次进展
渐次进展 2021-02-06 23:14

For example, I have a code looks like this:

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

How can I get something like this:

[(1,4), (1,5), (2,4), (2,5         


        
4条回答
  •  被撕碎了的回忆
    2021-02-07 00:08

    If you're interested only in the result, then itertools.product is what you need (+1 to @DSM for this). However, if you're interested in the algorithm that generates something like this, it's called recursive descent. The algorithm, in this case, would run as follows (I'm just going to print the results here for clarity):

    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])
    

    Thus,

    >>> product([[1,2], [4,5]])
    [1, 4]
    [1, 5]
    [2, 4]
    [2, 5]
    

    Hope this helps

提交回复
热议问题