2个列表的组合

Kyl*_*e K 5 python combinations list

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

Expected Output: [(1,a),(1,b),(2,a),(2,b),(3,a),(3,b)]
Run Code Online (Sandbox Code Playgroud)

这是有效的,但是没有 if 语句有更好的方法吗?

[(x,y) for (x,y) in list(combinations(chain(a,b), 2)) if x in a and y in b]
Run Code Online (Sandbox Code Playgroud)

sch*_*ggl 16

使用itertools.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')]
Run Code Online (Sandbox Code Playgroud)