【问题标题】:How to get all possible unique variants from all possible combinations如何从所有可能的组合中获得所有可能的独特变体
【发布时间】:2020-07-07 09:04:24
【问题描述】:

我有一个积分列表

lst = [1,2,3,4,5]

使用 itertools 我得到所有可能的行组合 ((1,2)=(2,1)):itertools.combinations(lst, 2)

[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

我想获取元组列表(具有唯一点),像这样

   [
    [(1,2),(3,4)],
    [(1,2),(3,5)],
    [(1,2),(4,5)],
    [(1,3),(2,4)],
    [(1,3),(2,5)],
    ...
    [(2,3),(4,5)]
   ]

【问题讨论】:

    标签: python combinations


    【解决方案1】:

    好的,这很有趣 xD。您需要的一切都由 itertools 提供,您只需以正确的方式组合它。看看这个:

    import itertools
    
    
    lst = [1,2,3,4,5]
    
    points = list(itertools.combinations(lst, 2))
    # [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
    
    f = lambda p: filter(lambda sub: not any(x in sub for x in p), points)
    
    res = []
    for p in points:
        res.extend(list(itertools.product([p], f(p))))
    
    # corresponding list-comprehension solution
    # res = list(itertools.chain.from_iterable(itertools.product([p], f(p)) for p in points))
    

    返回:

    res = [((1, 2), (3, 4)), ((1, 2), (3, 5)), ((1, 2), (4, 5)), ((1, 3), (2, 4)), ((1, 3), (2, 5)), ((1, 3), (4, 5)), ((1, 4), (2, 3)), ((1, 4), (2, 5)), ((1, 4), (3, 5)), ((1, 5), (2, 3)), ((1, 5), (2, 4)), ((1, 5), (3, 4)), ((2, 3), (1, 4)), ((2, 3), (1, 5)), ((2, 3), (4, 5)), ((2, 4), (1, 3)), ((2, 4), (1, 5)), ((2, 4), (3, 5)), ((2, 5), (1, 3)), ((2, 5), (1, 4)), ((2, 5), (3, 4)), ((3, 4), (1, 2)), ((3, 4), (1, 5)), ((3, 4), (2, 5)), ((3, 5), (1, 2)), ((3, 5), (1, 4)), ((3, 5), (2, 4)), ((4, 5), (1, 2)), ((4, 5), (1, 3)), ((4, 5), (2, 3))]
    

    它基本上归结为itertools.combinations(你已经做过)和itertools.product。扭曲是在两者之间执行的过滤(请参阅f = lambda ...)。如果您在理解代码方面需要进一步帮助,请告诉我。

    【讨论】:

      猜你喜欢
      • 2012-11-25
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 2019-10-25
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多