繁体   English   中英

如何从 python 元组列表中获取所有可能的组合

[英]How to get all possible combinations from python list of tuples

我有一个这样的清单..

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

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

我预期的 output 应该如下所示。

[
    [
        ("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 但我无法得到我预期的 output 不确定我错过了什么,找不到逻辑,请帮忙。 提前致谢。

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

提前致谢,

你想要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))]

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

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

如果您真的想使用组合,并获得显示的 output 格式,您可以执行类似的操作

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)
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM