Python中的组合列表

问题描述 投票:0回答:2

假设我有一个像这样的数据列表[['a', 'a', 'b'], ['a', 'a', 'b','b']]

我想输出a = 1 or 2, b = 3 or 4的所有排列的列表

对于['a', 'a', 'b'],输出:

[1,1,3]
[2,1,3]
[1,2,3]
[2,2,3]
[1,1,4]
[2,1,4]
[1,2,4]
[2,2,4]

我该如何做?谢谢您的帮助

python combinations factorial
2个回答
1
投票

您可以使用itertools.permutations找到列表的所有排列:

itertools.permutations

在您的情况下,您想测试>> import itertools >> list(itertools.permutations(['a', 'a', 'b']) [('a', 'a', 'b'), ('a', 'b', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a'), ('b', 'a', 'a'), ('b', 'a', 'a')] a之间值的所有组合,因此对于第一种情况:

b

您的第二种情况将是相同的,但是您需要相应地调整import itertools for a in range(1, 3): # a is 1 or 2 for b in range(3, 5): # b is 3 or 4 # Construct your list for this combination of values of a and b l = [a, a, b] # Find all permutations and print them print(list(itertools.permutations(l)) 变量。


0
投票

如果您的输入结构略有不同,则可以使用以下方法:

l

打印:

from itertools import product

values = {
    'a': [1, 2],
    'b': [3, 4]
}

case = ['a', 'a', 'b']

coms = product(*[values[c] for c in case])

for c in coms:

    print(list(c))
© www.soinside.com 2019 - 2024. All rights reserved.