从列表中获取所有不同的组合(Python)?

时间:2018-11-02 23:28:30

标签: python list iterator iteration combinations

我有以下两个词典:

a={"ad":["tau","guru"],
"bigd":["tau","guru"],
"lugd":["tau","guru"]}

b={"tau":["ad","bigd","lugd"],
"guru":["bigd","ad","lugd"]}

键的每个值都是键的优先顺序。我试图用python完成的是如何获得偏好顺序的所有可能组合。 因此,一种优先顺序是,当您仅翻转键“ ad”的值时,其余的将是相同的。它在下面列出

a={"ad":["guru", "tau"],
"bigd":["tau","guru"],
"lugd":["tau","guru"]}

b={"tau":["ad","bigd","lugd"],
"guru":["bigd","ad","lugd"]}

其他可能是“广告”偏好设置保持不变而“大”偏好设置不同的时候。我们必须遍历两个词典中的所有列表,并找到所有2 ^ 3 * 3 * 2的可能性。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您可以使用itertools来获得它们:

from itertools import permutations, product

a_variants = [dict(zip(["ad", "bigd", "lugd"], values)) 
                 for values in product(permutations(["tau","guru"]), repeat=3)]
b_variants = [dict(zip(["tau", "guru"], values)) 
                 for values in product(permutations(["ad", "bigd", "lugd"]), repeat=2)]

all_variants = product(a_variants, b_variants)

for va, vb in all_variants:
    print("a:", va, "\nb:", vb, "\n")

输出:

a: {'ad': ('tau', 'guru'), 'bigd': ('tau', 'guru'), 'lugd': ('tau', 'guru')} 
b: {'tau': ('ad', 'bigd', 'lugd'), 'guru': ('ad', 'bigd', 'lugd')} 

a: {'ad': ('tau', 'guru'), 'bigd': ('tau', 'guru'), 'lugd': ('tau', 'guru')} 
b: {'tau': ('ad', 'bigd', 'lugd'), 'guru': ('ad', 'lugd', 'bigd')} 

...

a: {'ad': ('guru', 'tau'), 'bigd': ('guru', 'tau'), 'lugd': ('guru', 'tau')} 
b: {'tau': ('lugd', 'bigd', 'ad'), 'guru': ('lugd', 'ad', 'bigd')} 

a: {'ad': ('guru', 'tau'), 'bigd': ('guru', 'tau'), 'lugd': ('guru', 'tau')} 
b: {'tau': ('lugd', 'bigd', 'ad'), 'guru': ('lugd', 'bigd', 'ad')} 

请注意,您有2 ** 3 *(3 * 2)** 2 = 288个不同的输出。