【问题标题】:How to get all possible combinations from python list of tuples如何从python元组列表中获取所有可能的组合
【发布时间】:2022-01-09 17:25:11
【问题描述】:

我有一个这样的列表..

[
    [
        ("a", 1)
    ] ,
    [
        ("b", 2)
    ],
    [
        ("c", 3),
        ("d", 4)
    ],
    [
        ("e", 5),
        ("f", 6),
        ("g", 7)
    ]
    
]

我正在尝试从此列表数据中获取所有可能的组合。

我的预期输出应该如下所示。

[
    [
        ("a", 1),
        ("b", 2),
        ("c", 3),
        ("e", 5)
    ],
        [
        ("a", 1),
        ("b", 2),
        ("c", 3),
        ("f", 6)
    ],
    [
        ("a", 1),
        ("b", 2),
        ("c", 3),
        ("g", 7)
    ],
    [
        ("a", 1),
        ("b", 2),
        ("d", 4),
        ("e", 5)
    ],
    [
        ("a", 1),
        ("b", 2),
        ("d", 4),
        ("f", 6)
    ],
    [
        ("a", 1),
        ("b", 2),
        ("d", 4),
        ("g", 7)
    ],
]

我尝试使用 itertools.combinations 但无法获得预期的输出,不确定我缺少什么,无法找到逻辑,请提供帮助。提前致谢。

如果您需要任何其他信息,请告诉我,

提前致谢,

【问题讨论】:

  • 意外的并发症是什么?

标签: python python-3.x list tuples combinations


【解决方案1】:

你想要itertools.product,而不是itertools.combinations。每个元组列表都应该是product 的一个参数,因此请使用* 运算符将起始列表的每个元素作为参数传递:

>>> import itertools
>>> list(itertools.product(*lists_of_tuples))
[(('a', 1), ('b', 2), ('c', 3), ('e', 5)), (('a', 1), ('b', 2), ('c', 3), ('f', 6)), (('a', 1), ('b', 2), ('c', 3), ('g', 7)), (('a', 1), ('b', 2), ('d', 4), ('e', 5)), (('a', 1), ('b', 2), ('d', 4), ('f', 6)), (('a', 1), ('b', 2), ('d', 4), ('g', 7))]

【讨论】:

    【解决方案2】:

    如果你真的想使用组合,并获得显示的输出格式,你可以这样做

    from itertools import combinations
    
    input_list = [
        [("a", 1)],
        [("b", 2)],
        [("c", 3), ("d", 4)],
        [("e", 5), ("f", 6), ("g", 7)],
    ]
    
    list_for_combos = [i[n] for i in input_list for n, _ in enumerate(i)]
    
    combos = list(
        [combo[n] for n, _ in enumerate(combo)]
        for combo in combinations(list_for_combos, 4)
    )
    

    【讨论】:

      【解决方案3】:

      我认为 itertools.products() 应该可以工作
      也因为您希望将结果作为 2d 列表,这应该可以正常工作。

      [list(x) for x in itertools.product(*li)]  # li is your list
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-14
        • 1970-01-01
        • 1970-01-01
        • 2010-10-02
        • 1970-01-01
        相关资源
        最近更新 更多