Python 将两个列表l1 x l2组合成元组
在一行中,我如何生成一个包含所有l1 x l2对元组的列表 例如: [1,2]et['a','b']->[(1,'a'),(1,'b'),(2,'a'),(2,'b')]Python 将两个列表l1 x l2组合成元组,python,list,Python,List,在一行中,我如何生成一个包含所有l1 x l2对元组的列表 例如: [1,2]et['a','b']->[(1,'a'),(1,'b'),(2,'a'),(2,'b')] 我尝试使用map()和zip(),但还没有找到答案。您可以使用列表理解 list3 = [(l1,l2) for l1 in list1 for l2 in list2] numbers = [1,2] letters = ['a','b'] new = [(num,letter) for num in numbers f
我尝试使用map()和zip(),但还没有找到答案。您可以使用列表理解
list3 = [(l1,l2) for l1 in list1 for l2 in list2]
numbers = [1,2]
letters = ['a','b']
new = [(num,letter) for num in numbers for letter in letters]
就这么简单。
下面是listcomprehension中的双重迭代示例
list3 = [(l1,l2) for l1 in list1 for l2 in list2]
numbers = [1,2]
letters = ['a','b']
new = [(num,letter) for num in numbers for letter in letters]
输出
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
您可以使用
itertools.product
from itertools import product
numbers = [1,2]
letters = ['a','b']
result = list(product(numbers,letters))
您需要列表的乘积。