【发布时间】:2017-10-24 19:10:06
【问题描述】:
Input: [1, 2, 3] [a, b]
Expected Output: [(1,a),(1,b),(2,a),(2,b),(3,a),(3,b)]
这可行,但是没有 if 语句有没有更好的方法?
[(x,y) for (x,y) in list(combinations(chain(a,b), 2)) if x in a and y in b]
【问题讨论】:
-
[(x,y) for x in a for y in b]? -
你可以使用itertools.product():
list(x for x in itertools.product([1, 2, 3], ['a', 'b'])) -
@jszakmeister 或者只是
list(itertools.product([1, 2, 3], ['a', 'b'])), ;) -
感谢 Wondercricket,这正是我想要的。 @schwobaseggl 产品是否适用于 n 个列表?像 [a][b][c] 的 (a,b,c),[a][b][c][d] 的 (a,b,c,d) 等等?
-
叹息。我认为引用的问题实际上与这个问题不够相似。 :-(
zip()在这里是错误的解决方案,map()也不一定是更好的解决方案。
标签: python list combinations