简体   繁体   中英

All possible combinations of subvalues in a list

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

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']
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')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM