1

I'm working on how to generate all possible combinations of subvalues in a list.

For instance if I have the list: ['abc', 'def', 'ghi', 'jkl'], I'm trying to generate a matrix of all possible combinations of values that do not include the first element changing while also appending the first element to the end of the list.

Desired output:

['abc','def','ghi','jkl','abc']
['abc','def','jkl','ghi','abc']
['abc','ghi','def','jkl','abc']
['abc','ghi','jkl','def','abc']
['abc','jkl','ghi','def','abc']
['abc','jkl','def','ghi','abc']

I tried working with itertools but I'm relatively new to the package. It seems to work for each individual character of the list, but not the value as a whole:

Current code:

buildings=['abc', 'def', 'ghi', 'jkl']
for t in itertools.product(*buildings):
    print(t)

Current Output:

('a', 'd', 'g', 'j')
('a', 'd', 'g', 'k')
('a', 'd', 'g', 'l')
('a', 'd', 'h', 'j')
and so on
TylerH
  • 20,799
  • 66
  • 75
  • 101
peakstatus
  • 381
  • 1
  • 3
  • 15
  • Does this answer your question? [How to generate all permutations of a list?](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list) – PM 77-1 Mar 31 '20 at 21:00

2 Answers2

3

You should use itertools.permutations instead for your purpose:

from itertools import permutations
first, *rest = buildings
for p in permutations(rest):
    print([first, *p, first])

This outputs:

['abc', 'def', 'ghi', 'jkl', 'abc']
['abc', 'def', 'jkl', 'ghi', 'abc']
['abc', 'ghi', 'def', 'jkl', 'abc']
['abc', 'ghi', 'jkl', 'def', 'abc']
['abc', 'jkl', 'def', 'ghi', 'abc']
['abc', 'jkl', 'ghi', 'def', 'abc']
blhsing
  • 91,368
  • 6
  • 71
  • 106
0
import itertools
 tab = ['abc', 'def', 'ghi', 'jkl']
 print(list(itertools.permutations(tab,len(tab))))
 [('abc', 'def', 'ghi', 'jkl'), ('abc', 'def', 'ghi', 'jkl'), ('abc',
 'def', 'ghi', 'jkl'), ('abc', 'def', 'ghi', 'jkl'), ('abc', 'def',
 'ghi', 'jkl'), ('abc', 'def', 'ghi', 'jkl'), ('abc', 'def', 'ghi',
 'jkl'), ('abc', 'def', 'ghi', 'jkl'), ('abc', 'def', 'ghi', 'jkl'),
 ('abc', 'def', 'ghi', 'jkl'), ('abc', 'def', 'ghi', 'jkl'), ('abc',
 'def', 'ghi', 'jkl'), ('abc', 'def', 'ghi', 'jkl'), ('abc', 'def',
 'ghi', 'jkl'), ('abc', 'def', 'ghi', 'jkl'), ('abc', 'def', 'ghi',
 'jkl'), ('abc', 'def', 'ghi', 'jkl'), ('abc', 'def', 'ghi', 'jkl'),
 ('abc', 'def', 'ghi', 'jkl'), ('abc', 'def', 'ghi', 'jkl'), ('abc',
 'def', 'ghi', 'jkl'), ('abc', 'def', 'ghi', 'jkl'), ('abc', 'def',
 'ghi', 'jkl'), ('abc', 'def', 'ghi', 'jkl')]
M--
  • 25,431
  • 8
  • 61
  • 93
Donka
  • 48
  • 6