Home > OS >  Given a List get all the combinations of tuples without duplicated results
Given a List get all the combinations of tuples without duplicated results

Time:10-21

I have a list=[1,2,3,4] And I only want to receive tuple results for like all the positions in a matrix, so it would be

(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4)

I've seen several codes that return all the combinations but i don't know how to restrict it only to the tuples or how to add the (1,1),(2,2),(3,3),(4,4)

Thank you in advance.

CodePudding user response:

You just need a double loop. A generator makes it easy to use

lst = [1,2,3,4]

def matrix(lst):
    for i in range(len(lst)):
        for j in range(len(lst)):
            yield lst[i], lst[j]

output = [t for t in matrix(lst)]

print(output)

Output:

[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]

CodePudding user response:

If you just want to do this for making pairs of all symbols in the list

tuple_pairs = [(r,c) for r in lst for c in lst]

If you have instead some maximum row/colum numbers max_row and max_col you could avoid making the lst=[1,2,3,4] and instead;

tuple_pairs = [(r,c) for r in range(1,max_row 1) for c in range(1,max_col 1)]

But that's assuming that the lst's goal was to be = range(1, some_num).

CodePudding user response:

You can do that using list comprehension.

lst=[1,2,3,4]

out=[(i,i) for i in lst]

print(out)

Output:

[(1, 1), (2, 2), (3, 3), (4, 4)]

CodePudding user response:

Use itertools.product to get all possible combinations of an iterable object. product is roughly equivalent to nested for-loops with depth specified by the keyword parameter repeat. It returns an iterator.

from itertools import product

lst = [1, 2, 3, 4]

combos = product(lst, repeat=2)
combos = list(combos) # cast to list
print(*combos, sep=' ')

Diagonal terms can be found in a single loop (without any extra imports)

repeat = 2
diagonal = [(i,)*repeat for i in lst]
print(*diagonal sep=' ')
  • Related