Python getting unique pairs from multiple lists of different lengths -


suppose in python have 3 lists: a, b, c of variable lengths. example :

a=[1,2,3] b=[4,5,6] c=[7,8] 

i every unique combination of 2 elements of 3 lists above, i. e.

[1,4],[1,5],[1,6],[1,7],[1,8],[2,4],[2,5]... , not unique combinations of 3 lists (such [1,4,7],[1,4,8],...).

i have looked @ solution here using itertools fine 2 lists ; however, solution not work anymore when including nth list because unique combinations of length n.

here have tried:

import itertools  a=[1,2,3] b=[4,5,6] c=[7,8]  d=list(itertools.product(a,b,c))  [(1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (1, 6, 7), (1, 6, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (2, 6, 7), (2, 6, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8), (3, 6, 7), (3, 6, 8)] 

note: above example , solution should work n lists of variable length , possibly same value being in different lists... idea of how appreciated! :)


edit: asked @sirparselot, elements have come different lists

you want cartesian product of each pair of lists in (a, b, c), first need itertools.combinations generate pairs of lists, , itertools.product create desired output tuples.

from itertools import combinations, product  def pairs(*lists):     t in combinations(lists, 2):         pair in product(*t):             yield pair  = [1, 2, 3] b = [4, 5, 6] c = [7, 8]  pair in pairs(a, b, c):     print(pair) 

output

(1, 4) (1, 5) (1, 6) (2, 4) (2, 5) (2, 6) (3, 4) (3, 5) (3, 6) (1, 7) (1, 8) (2, 7) (2, 8) (3, 7) (3, 8) (4, 7) (4, 8) (5, 7) (5, 8) (6, 7) (6, 8) 

here's new version handles repeated elements. not return tuple if 2 items in tuple equal each other, , eliminates duplicated tuples in output feeding output pairs set. reasonably efficient since pairs generator, duplicates eliminated found.

from itertools import combinations, product  def pairs(*lists):     t in combinations(lists, 2):         pair in product(*t):             #don't output pairs containing duplicated elements              if pair[0] != pair[1]:                 yield pair  = [1, 2, 3] b = [3, 4, 5] c = [5, 6]  #feed output of `pairs` set eliminate duplicate tuples output = set(pairs(a, b, c)) pair in sorted(output):     print(pair) 

output

(1, 3) (1, 4) (1, 5) (1, 6) (2, 3) (2, 4) (2, 5) (2, 6) (3, 4) (3, 5) (3, 6) (4, 5) (4, 6) (5, 6) 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -