0

I have few lists:

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

How do I generate all combinations like:

a[0], b[0]
a[1], b[1]
a[2], b[2]
a[0], b[0], c[0]
a[1], b[1], c[0]
a[2], b[2], c[0]
a[1], b[1], c[1]
a[2], b[2], c[2]
a[0], b[0], c[3]
a[1], b[1], c[3]
a[2], b[2], c[3]
.....

There can be only one value at a time from each list.

Imagine two or more lists Like a=[1,2,3] and b=[4,5,6] and c=[7,8,9] and I would like all possible pairs like (a[0], b[0]),(a[1], b[1]), (a[0], b[0], c[0])...

Jongware
  • 22,200
  • 8
  • 54
  • 100
Konrad
  • 6,385
  • 12
  • 53
  • 96
  • 2
    [`itertools.permutations`](https://docs.python.org/library/itertools.html#itertools.permutations), with length required. Also duplicate of https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python?rq=1 as per side bar. – metatoaster Aug 28 '16 at 09:58
  • 1
    What's so unusual in this, and how is this different than all the other permutations questions on SO? – DeepSpace Aug 28 '16 at 09:59
  • I want a* to occur only once in a list. It can't be a1, a2, a3 or b1,b2,c1 – Konrad Aug 28 '16 at 10:21
  • Is things like `'a1'` your real string pattern, that is, how can you specify what is `'a'` and `'*'` in your real scene? – YiFei Aug 28 '16 at 10:22
  • @YiFei I've got a list like a=[1,2,3] and b=[4,5,6] and I would like all possible pairs like a[0], b[0], a[1], b[1] and so on. – Konrad Aug 28 '16 at 10:24
  • 1
    You should probably use `itertools.product` for this, but it's still not clear exactly what combinations you want. Should the output contain (a[0], c[0]) or (b[0], c[0])? BTW, (a[0], b[0], c[0]) contains 3 items so it is not a pair. – PM 2Ring Aug 28 '16 at 10:43
  • @PM2Ring yes I wanted product for this. I know it's not a pair just tried to explain what I mean. Thanks – Konrad Aug 28 '16 at 10:46

2 Answers2

1

As per your example, you seem to want only abc-type permutations. So you either: 1) build your "permutations" explicitly, or 2) build all permutations and filter out those you do not want.

Explicit construction

  1. Build your list_of_lists, i.e. [['a1', 'a2', 'a3'], ['b1', 'b2'], ['c1']]
  2. Build your permutations. Use itertools.product, see All combinations of a list of lists
  3. From each of your permutations, you might want to create several, within a loop. E.g., from ('a1','b1','c1') get ('a1','b1','c1') and ('a1','b1'). That is easy.

You can fill in the gaps.

Build all and filter out

... Probably only useful if you need something (slightly) different from what I understood.

Community
  • 1
  • 1
0

Not sure whether I've understood correctly your question, but do you mean this?

from itertools import permutations

my_list = ['a1', 'a2', 'a3', 'b1', 'b2', 'c1']

for i in range(len(my_list)):
    print(list(permutations(my_list, i)))
BPL
  • 9,632
  • 9
  • 59
  • 117