DJA
DJA

Reputation: 173

Pairing up all possible objects in a list

Consider the following code:

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

This will result in a list being formed as follows:

[[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]]             

Whereby each number is paired with another number in the list and no repeats i.e. if [1,2] exists then [2,1] will not be created also pairs with two of the same numbers e.g. [1,1] will not be created either.

However now consider a list of objects whereby I would like to pair each object with one other object (not itself and no repeats) in a similar fashion as the numbers were. For some reason my code does not allow me to do that as it presents a message '>' not supported between instances of 'Ball' and 'Ball'. (The class I created was called Ball which generated the objects).

Any help to resolve this issue would be very much appreciated.

Upvotes: 1

Views: 250

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36702

Of course, itertools is the proper "pythonic" solution:

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

However, you have the correct idea, you can generate all the indices of the objects to be paired, and retrieve them:

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)

output:

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

Upvotes: 2

Related Questions