[英]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.例如,如果我有以下列表:
['abc', 'def', 'ghi', 'jkl']
,我正在尝试生成所有可能的值组合的矩阵,其中不包括第一个元素的变化,同时也将第一个元素附加到列表的末尾。
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.我尝试使用 itertools,但我对这个包比较陌生。 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:您应该使用
itertools.permutations
代替您的目的:
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')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.