简体   繁体   中英

How to combine two lists together into a list of tuples using recursion?

I know that this doesn't have to be done by doing recursion. I want to combine two lists such as x = [0, 1] and y = ['a', 'b', 'c'] and create a function that puts them in a list of tuples such as: [(0, 'a'), (0, 'b'), (0, 'c'), (1, 'a'), (1, 'b'), (1, 'c')] .

I know only how to do this for the first index of list x and struggling to figure out how to move on to further indexes. The output for the function below is: [(0, 'a'), (0, 'b'), (0, 'c')] .

def combine(x, y, idx=0):
    if idx < len(y):
        return [(x[idx], y[idx])] + combine(x, y[1:])
    else:
        return []

I don't know how to get to get the list x to move onto further indexes. I think I may need to call all_pairs(list1, list2, index+1 instead of slicing the list. Do I need to have the function call itself twice? This may seem elementary but for whatever reason I can't figure it out.

You can do as below

from itertools import product
a = list(product(x,y))
a

or just list comprehension as below

[(a,b) for a in x for b in y]

Output

[(0, 'a'), (0, 'b'), (0, 'c'), (1, 'a'), (1, 'b'), (1, 'c')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM