Search code examples
pythonpython-3.xloopsmultidimensional-arraypython-itertools

Match each sublist item with every item in every other sublist (python)


I have a list of lists of boards, boards. boards contains a number of sublists that each have the same type of board in them. Essentially: [[...], [...], ...].

Say the first sublist was 1 and the second sublist was 2. I need to compare the each element of 1 to each element of 2. So, I need the pairs (1[0], 2[0]), (1[0], 2[1])...(1[0], 2[len(2)-1]);(1[0], 2[0])....

The problem is, I don’t know how many sublists are in boards, meaning I can’t just do n for loops. This is what I have right now:

for sublist in boards:
    for board in sublist:
        for board_indices in itertools.permutations(range(len(sublist)), len(boards)):
            matched_boards = [boards[a][j] for a, j in enumerate(i)]

But I think I’m overthinking it. I am sure there is an easier, simpler, more readable way to do this but I’m not sure what it is.


Solution

  • If it's only pairs you want, you could combine itertools.combinations with itertools.product to give every possible cross-sublist pair:

    for sublist_pair in itertools.combinations(nested_iter, 2):
        for item_pair in itertools.product(*sublist_pair):
            print(item_pair)
    

    Giving:

    (1, 'a')
    (1, 'b')
    (1, 'c')
    (2, 'a')
    (2, 'b')
    (2, 'c')
    (3, 'a')
    (3, 'b')
    (3, 'c')
    (1, 0.1)
    (1, 0.2)
    (1, 0.3)
    (2, 0.1)
    (2, 0.2)
    (2, 0.3)
    (3, 0.1)
    (3, 0.2)
    (3, 0.3)
    ('a', 0.1)
    ('a', 0.2)
    ('a', 0.3)
    ('b', 0.1)
    ('b', 0.2)
    ('b', 0.3)
    ('c', 0.1)
    ('c', 0.2)
    ('c', 0.3)