Combinations between two lists?

It has been a while, and I am having trouble wrapping around the algorithm I'm trying to do. Basically, I have two lists and you want to get all combinations of these two lists.

Maybe I wonโ€™t explain it correctly, so here is an example.

name = 'a', 'b' number = 1, 2 

the output in this case will be:

 1. A1 B2 2. B1 A2 

The hard part: I can have more elements in the variable "name" than in the variable "number" (the number will always be equal to or less than the variable name).

I got confused how to make all combinations (nested in a loop?) And even more confused with logic to move elements in a name variable in case there are more elements in the list than in the list of numbers.

I am not the best programmer, but I think I can give him a chance if someone can help me clarify the logic / algorithm to achieve this. So I was just stuck on nested loops.

Update:

Here is the output with three variables and two numbers:

 name = 'a', 'b', 'c' number = 1, 2 

exit:

 1. A1 B2 2. B1 A2 3. A1 C2 4. C1 A2 5. B1 C2 6. C1 B2 
+148
python list algorithm combinations
Oct 17
source share
11 answers

Suppose len(list1) >= len(list2) . Then you need to take all permutations of length len(list2) from list1 and map them to elements from list2. In python:

 import itertools list1=['a','b','c'] list2=[1,2] [zip(x,list2) for x in itertools.permutations(list1,len(list2))] 

Returns

 [[('a', 1), ('b', 2)], [('a', 1), ('c', 2)], [('b', 1), ('a', 2)], [('b', 1), ('c', 2)], [('c', 1), ('a', 2)], [('c', 1), ('b', 2)]] 
+72
Oct 17 '12 at 13:35
source share

The easiest way is to use itertools.product :

 a = ["foo", "melon"] b = [True, False] c = list(itertools.product(a, b)) >> [("foo", True), ("foo", False), ("melon", True), ("melon", False)] 
+413
Dec 01 '15 at 23:57
source share

Could be simpler than simple above:

 >>> a = ["foo", "bar"] >>> b = [1, 2, 3] >>> [(x,y) for x in a for y in b] [('foo', 1), ('foo', 2), ('foo', 3), ('bar', 1), ('bar', 2), ('bar', 3)] 

without any import

+129
Aug 21 '16 at 13:33
source share

I was looking for a list multiplied by itself with only unique combinations, which is provided as this function.

 import itertools itertools.combinations(list, n_times) 



Here is an excerpt from the Python documentation for itertools This may help you find what you are looking for.

 Combinatoric generators: Iterator | Results -----------------------------------------+---------------------------------------- product(p, q, ... [repeat=1]) | cartesian product, equivalent to a | nested for-loop -----------------------------------------+---------------------------------------- permutations(p[, r]) | r-length tuples, all possible | orderings, no repeated elements -----------------------------------------+---------------------------------------- combinations(p, r) | r-length tuples, in sorted order, no | repeated elements -----------------------------------------+---------------------------------------- combinations_with_replacement(p, r) | r-length tuples, in sorted order, | with repeated elements -----------------------------------------+---------------------------------------- product('ABCD', repeat=2) | AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD permutations('ABCD', 2) | AB AC AD BA BC BD CA CB CD DA DB DC combinations('ABCD', 2) | AB AC AD BC BD CD combinations_with_replacement('ABCD', 2) | AA AB AC AD BB BC BD CC CD DD 
+16
Nov 29 '16 at 21:52
source share

You might want to try a one-line schedule:

 >>> [name+number for name in 'ab' for number in '12'] ['a1', 'a2', 'b1', 'b2'] >>> [name+number for name in 'abc' for number in '12'] ['a1', 'a2', 'b1', 'b2', 'c1', 'c2'] 
+11
Jan 10 '17 at 19:26
source share

a slight improvement in the response from interjay to make the result a smoothing list.

 >>> list3 = [zip(x,list2) for x in itertools.permutations(list1,len(list2))] >>> import itertools >>> chain = itertools.chain(*list3) >>> list4 = list(chain) [('a', 1), ('b', 2), ('a', 1), ('c', 2), ('b', 1), ('a', 2), ('b', 1), ('c', 2), ('c', 1), ('a', 2), ('c', 1), ('b', 2)] 

link from this link

+9
Dec 19 '13 at 15:02
source share

Without itertools

 [(list1[i], list2[j]) for i in xrange(len(list1)) for j in xrange(len(list2))] 
+4
Mar 11 '16 at 11:32
source share

Answering the question โ€œgiven two lists, find all possible permutations of pairs of one element from each listโ€ and using the basic Python functionality (i.e. without itertools) and, therefore, simplify its replication for other programming languages:

 def rec(a, b, ll, size): ret = [] for i,e in enumerate(a): for j,f in enumerate(b): l = [e+f] new_l = rec(a[i+1:], b[:j]+b[j+1:], ll, size) if not new_l: ret.append(l) for k in new_l: l_k = l + k ret.append(l_k) if len(l_k) == size: ll.append(l_k) return ret a = ['a','b','c'] b = ['1','2'] ll = [] rec(a,b,ll, min(len(a),len(b))) print(ll) 

Returns

 [['a1', 'b2'], ['a1', 'c2'], ['a2', 'b1'], ['a2', 'c1'], ['b1', 'c2'], ['b2', 'c1']] 
+4
Mar 11 '18 at 10:11
source share

Or KISS answer for short lists:

 [(i, j) for i in list1 for j in list2] 

Not as productive as itertools, but you are using python, so performance is no longer your main concern ...

I like all the other answers too!

+3
Jul 29 '19 at 17:50
source share

The best way to find out all the combinations for a large number of lists:

 import itertools from pprint import pprint inputdata = [ ['a', 'b', 'c'], ['d'], ['e', 'f'], ] result = list(itertools.product(*inputdata)) pprint(result) 

the result will be:

 [('a', 'd', 'e'), ('a', 'd', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f')] 
+2
Jul 24 '19 at 9:07
source share

The best answers to this question are only suitable for the specific lengths of the lists that are provided.

Here is a version that works for any input length. It also makes the algorithm understandable in terms of mathematical concepts of combination and permutation.

 from itertools import combinations, permutations list1 = ['1', '2'] list2 = ['A', 'B', 'C'] num_elements = min(len(list1), len(list2)) list1_combs = list(combinations(list1, num_elements)) list2_perms = list(permutations(list2, num_elements)) result = [ tuple(zip(perm, comb)) for comb in list1_combs for perm in list2_perms ] for idx, ((l11, l12), (l21, l22)) in enumerate(result): print(f'{idx}: {l11}{l12} {l21}{l22}') 

This outputs:

 0: A1 B2 1: A1 C2 2: B1 A2 3: B1 C2 4: C1 A2 5: C1 B2 
+2
Aug 05 '19 at 16:12
source share



All Articles