代码之家  ›  专栏  ›  技术社区  ›  DJA

将列表中所有可能的对象配对

  •  1
  • DJA  · 技术社区  · 7 年前

    考虑以下代码:

    list_example = [1,2,3,4,5,6,7,8,9]
    List_of_ball_permutations = []
    
        for i in list_example :
           for j in list_example:
               if j>i:
                   List_of_ball_permutations.append([i,j])
    

    这将导致形成如下列表:

    [[1, 2],
     [1, 3],
     [1, 4],
     [1, 5],
     [1, 6],
     [1, 7],
     [1, 8],
     [1, 9],
     [2, 3],
     [2, 4],
     [2, 5],
     [2, 6],
     [2, 7],
     [2, 8],
     [2, 9],
     [3, 4],
     [3, 5],
     [3, 6],
     [3, 7],
     [3, 8],
     [3, 9],
     [4, 5],
     [4, 6],
     [4, 7],
     [4, 8],
     [4, 9],
     [5, 6],
     [5, 7],
     [5, 8],
     [5, 9],
     [6, 7],
     [6, 8],
     [6, 9],
     [7, 8],
     [7, 9],
     [8, 9]]             
    

    其中,每个数字与列表中的另一个数字配对,并且没有重复,即如果[1,2]存在,则不会创建[2,1],也不会创建与两个相同数字配对的数字,例如[1,1]。

    然而,现在考虑一个对象列表,其中我希望以与数字类似的方式将每个对象与另一个对象配对(不是本身,也没有重复)。由于某种原因,我的代码不允许这样做,因为它显示了一条消息“>”“Ball”和“Ball”实例之间不支持。(我创建的类称为Ball,它生成了对象)。

    如果能帮助解决这个问题,我们将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Reblochon Masque    7 年前

    当然 itertools 是正确的“pythonic”解决方案:

    import itertools
    list(itertools.combinations(["a", "b", "c"], 2))
    

    但是,如果您的想法正确,您可以生成要配对的对象的所有索引,并检索它们:

    def get_pairs(n):
        for i in range(n) :
            for j in range(i+1, n):
                yield (i, j)
    
    def get_objects_pairs(objects):
        for first, second in get_pairs(len(objects)):
            yield objects[first], objects[second]
    
    objects = ['a', 'ball', 'toothbrush']
    for pair in (get_objects_pairs(objects)):
        print(pair)
    

    输出:

    ('a', 'ball')
    ('a', 'toothbrush')
    ('ball', 'toothbrush')