Home > Blockchain >  How can i create a list of all possible combination between element of another list?
How can i create a list of all possible combination between element of another list?

Time:11-16

let's say we have a list , composed by integer number from 0 to another number larger than 0 :

list = [0,1,2,3...and so on]

I'd like to get a set or even a list, containing a list for all the pairs of possible combinations between the elements of the starting list. like that:

new_list = [[0,1],[0,2],[0,3],[1,0],[1,2],[1,3],[2,0],[2,1],[2,3],[3,0],[3,1],[3,2]]

As you can see the pairs [0,0],[1,1],[2,2],[3,3] must not be included.

I tried several thing but i end up nowhere . Do you know an effective way to do it?

CodePudding user response:

Use itertools.combinations and their reversals:

from itertools import combinations

combos = list(combinations(lst, 2))

new_list = [*combos, *(c[::-1] for c in combos)]

Or manually:

def pairings(pool):
    for i, m in enumerate(pool):
        for n in pool[i 1:]:
            yield (m, n)
            # yield (n, m)  # saves second loop if order does not matter
    for i, m in enumerate(pool):
        for n in pool[i 1:]:
            yield (n, m)

new_list = list(pairings(lst))

CodePudding user response:

You can use a simple list comprehension:

[[a, b] for a in lst for b in list if a != b]

CodePudding user response:

What about a simple nested loop comprehension or generator?

def comb_not_eq_loop(seq, container=list):
    return container(x, y) for x in seq for y in seq if x != y)


comb_not_eq_loop(list(range(3))
# [(0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (2, 1)]
def comb_not_eq_gen(seq):
    for x in seq:
        for y in seq:
            if x != y:
                yield (x, y)


list(comb_not_eq_gen(list(range(3)))
# [(0, 1), (0, 2), (1, 2), (1, 0), (2, 0), (2, 1)]
  • Related