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模块/方法?
答案 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