Combinations of 2 lists [duplicate]

一笑奈何 提交于 2019-12-13 11:21:50

问题


Input: [1, 2, 3] [a, b]

Expected Output: [(1,a),(1,b),(2,a),(2,b),(3,a),(3,b)]

This works, but is there a better way without an if statement?

[(x,y) for (x,y) in list(combinations(chain(a,b), 2)) if x in a and y in b]

回答1:


Use itertools.product, your handy library tool for a cartesian product:

from itertools import product

l1, l2 = [1, 2, 3], ['a', 'b']
output = list(product(l1, l2))
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]


来源:https://stackoverflow.com/questions/46918272/combinations-of-2-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!