【问题标题】:Generate combinations of elements from multiple lists从多个列表中生成元素组合
【发布时间】:2013-04-14 16:32:36
【问题描述】:

我正在制作一个函数,该函数将可变数量的列表作为输入(即arbitrary argument list)。 我需要将每个列表中的每个元素与所有其他列表中的每个元素进行比较,但我找不到任何方法来解决这个问题。

【问题讨论】:

    标签: python arrays for-loop args


    【解决方案1】:

    我认为@LevLeitsky 的回答是对可变数量列表中的项目进行循环的最佳方式。但是,如果循环的目的只是为了从列表中找到成对的项目之间的共同元素,我会做一些不同的事情。

    这是一种在每对列表之间找到共同元素的方法:

    import itertools
    
    def func(*args):
        sets = [set(l) for l in args]
        for a, b in itertools.combinations(sets, 2):
            common = a & b # set intersection
            # do stuff with the set of common elements...
    

    我不确定您需要对公共元素做什么,所以我将把它留在那里。

    【讨论】:

      【解决方案2】:

      itertools 模块为此类任务提供了许多有用的工具。您可以通过将以下示例集成到您的特定比较逻辑中来调整以下示例以适应您的任务。

      请注意,以下假设是一个交换函数。也就是说,由于对称性的原因,大约有一半的元组被省略了。

      例子:

      import itertools
      
      def generate_pairs(*args):
          # assuming function is commutative
          for i, l in enumerate(args, 1):
              for x, y in itertools.product(l, itertools.chain(*args[i:])):
                  yield (x, y)
      
      # you can use lists instead of strings as well
      for x, y in generate_pairs("ab", "cd", "ef"):
          print (x, y)
      
      # e.g., apply your comparison logic
      print any(x == y for x, y in generate_pairs("ab", "cd", "ef"))
      print all(x != y for x, y in generate_pairs("ab", "cd", "ef"))
      

      输出:

      $ python test.py
      ('a', 'c')
      ('a', 'd')
      ('a', 'e')
      ('a', 'f')
      ('b', 'c')
      ('b', 'd')
      ('b', 'e')
      ('b', 'f')
      ('c', 'e')
      ('c', 'f')
      ('d', 'e')
      ('d', 'f')
      False
      True
      

      【讨论】:

        【解决方案3】:

        如果你想要参数作为字典

        def kw(**kwargs):
            for key, value in kwargs.items():
                print key, value
        

        如果你想要所有的参数作为列表:

         def arg(*args):
                for item in args:
                    print item
        

        两个都可以用

        def using_both(*args, **kwargs) :
             kw(kwargs)
             arg(args)
        

        这样称呼:

        using_both([1,2,3,4,5],a=32,b=55)
        

        【讨论】:

          【解决方案4】:

          根据您的目标,您可以使用一些itertools 实用程序。例如,您可以在*args 上使用itertools.product

          from itertools import product
          for comb in product(*args):
              if len(set(comb)) < len(comb):
                  # there are equal values....
          

          但目前您的问题还不是很清楚您想要实现什么。如果我没有正确理解您的意思,您可以尝试以更具体的方式陈述问题。

          【讨论】:

            猜你喜欢
            • 2013-06-16
            • 1970-01-01
            • 1970-01-01
            • 2015-12-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多