【问题标题】:all combination in list of lists without duplicates in python在python中没有重复的列表列表中的所有组合
【发布时间】:2018-08-19 13:01:40
【问题描述】:

假设我有一个列表列表

[[a1, a2, a3], [b1, b2], [c1, c2, c3, c4]]

事先不知道列表中的列表数量。

我想拥有来自不同列表的所有元素组合,所以

[a1, b1, c1], [a1, b1, c2], ..., [a3, b2, c4] 

但如果不同列表中有共同的元素,则所有这些组合都需要删除。因此,例如a1 = c2,则需要在结果列表中删除组合[a1, b1, c2], [a1, b2, c2]

要获取所有可能的组合,可以使用All possible permutations of a set of lists in Python上的答案,但是可以自动删除所有具有共同元素的组合吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    正如其他人所说,您可以使用 itertools 但您可能需要删除重复项:

    import itertools
    
    L = [1,2,3,4]
    combos = list(itertools.combinations(L, 2))
    pairs = [[x, y] for x in combos for y in combos if not set(x).intersection(set(y))]
    list(set(sum(pairs, [])))
    

    然后你会得到这个作为输出:

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

    [编辑]

    灵感来自此处提供的答案:https://stackoverflow.com/a/42924469/8357763

    【讨论】:

      【解决方案2】:

      您正在寻找列表中的Cartesian Product。使用itertools.product(),并过滤元素以确保没有相等:

      from itertools import product
      
      for combo in product(*input_lists):
          if len(set(combo)) != len(combo):  # not all values unique
              continue
          print(*combo)
      

      我假设 a1 = c2 你的意思是组合中的所有值都需要是唯一的,上面通过从组合。如果设置的长度小于组合的长度,你有重复的值。

      您可以将此过滤器放入生成器函数中:

      def unique_product(*l, repeat=None):
          for combo in product(*l, repeat=repeat):
              if len(set(combo)) == len(combo):  # all values unique
                  yield combo
      

      然后使用for unique in unique_product(*input_lists):

      您也可以使用filter() function 来实现相同的目的,但这会为生成的每个组合产生一个函数调用。

      【讨论】:

        【解决方案3】:

        1) itertools.product

         all_combinations = itertools.product(elements)
        

        2) filter 带 lambda

        filtered_combinations = filter(lambda x: len(x) != len(set(x)), all_combinations)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多