我想编写一个函数"product",它将两个列表a和b作为参数,并返回一个列表,其中包含a和b中的所有元素对作为元组。 例如,我有a = ["a", "b"] and b = [1,2,3]
,我希望我的输出是[("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("b", 3)]
的。 我该怎么做? 我试过
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))
但我只得到 [('a', 1(, ('b', 2(] 作为输出。 我需要更改什么?我真的不明白我需要添加什么。我是 python 编程的新手,所以一开始这是一个艰巨的挑战,所以任何帮助将不胜感激!
您可以使用列表推导:
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))
map
对两个列表同步运行,类似于你编写
[(x,y) for x,y in zip(a, b)]
要获取所有可能的对,您需要以嵌套方式分别迭代这两个列表。
[(x,y) for x in a for y in b]
如果你想用嵌套的map
s来写这个(虽然我不推荐它(,你需要使用chain.from_iterable
来平展结果。
from itertools import chain
list(chain.from_iterable(map(lambda x: map(lambda y: (x,y), b), a)))