【问题标题】:Combinations of 2 lists [duplicate]2个列表的组合[重复]
【发布时间】: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


【解决方案1】:

使用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')]

【讨论】:

    猜你喜欢
    • 2013-06-05
    • 1970-01-01
    • 2019-03-04
    • 2015-09-02
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多