Python模块生成字符串中可能的字符串替换的所有排列?

时间:2014-07-08 14:45:02

标签: python itertools

template = "{{ person }} is a {{ quality }} {{ occupation }}"
replacements = {
"person":["John","Matt","Steve"],
"quality":["great","dedicated"],
"occupation":["engineer","student","athelete"]
}

Output:
John is a great engineer
Matt is a great engineer
Steve is a great engineer
John is a dedicated engineer
Matt is a dedicated engineer
Steve is a dedicated engineer
John is a great student
Matt is a great student
Steve is a great student
.............................

可以使用可替换元素列表列表生成它们,然后循环它们以生成排列,然后加入列表元素。

list_input =     [["John","Matt","Steve"],["is"],["a"],["great","dedicated"],["engineer","student","athelete"]]

example_permutation = ["John","is","a","great","engineer"]

是否有可以生成类似排列的python模块/方法?

1 个答案:

答案 0 :(得分:4)

这只是列表的cartesian product

import itertools

list_input =     [["John","Matt","Steve"],["is"],["a"],["great","dedicated"],["engineer","student","athelete"]]
for element in itertools.product(*list_input):
    print element

或者你可以直接从你的dict @dano(建议)

replacements = {
"person":["John","Matt","Steve"],
"quality":["great","dedicated"],
"occupation":["engineer","student","athelete"]
}

for element in itertools.product(*replacements.values()):
    print("{} is a {} {}".format(*element))


#output 

John is a great engineer
John is a great student
John is a great athelete
John is a dedicated engineer
John is a dedicated student
John is a dedicated athelete
Matt is a great engineer
Matt is a great student
Matt is a great athelete
Matt is a dedicated engineer
Matt is a dedicated student
Matt is a dedicated athelete
Steve is a great engineer
Steve is a great student
Steve is a great athelete
Steve is a dedicated engineer
Steve is a dedicated student
Steve is a dedicated athelete