简体   繁体   中英

Two lists of parameters to return a list of elements as tuples

I want to write a function "product" which takes two lists a and b as parameters and returns a list with all pairs of elements from a and b as tuples. For example, I have a = ["a", "b"] and b = [1,2,3] , and I want my output to be [("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("b", 3)] . How do I do that? I have tried with

def product(a, b): 
    return list(map(lambda x, y:(x,y), a, b)) 

a = ["a", "b"] 
b = [1, 2, 3] 

print(product(a, b))

but I get only [('a', 1), ('b', 2)] as an output. What do I need to change? I don't really understand what I need to add. I am new to programming in python so It's kind of a hard challenge in the beginning, so any help would be appreciated!

map operates over both lists in lockstep, similar to if you had written

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

To get all possible pairs, you need to iterate over both lists separately , in a nested fashion.

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

If you want to write this with nested map s (though I wouldn't recommend it), you'll want to use chain.from_iterable to flatten the result.

from itertools import chain
list(chain.from_iterable(map(lambda x: map(lambda y: (x,y), b), a)))

You could use list comprehension:

def product(a, b): 
    return [(a_, b_) for a_ in a for b_ in b]

a = ["a", "b"]
b = [1, 2, 3]

print(product(a, b))

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