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模块/方法?
发布于 2014-07-08 14:50:28
这就是名单上的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 atheletehttps://stackoverflow.com/questions/24634833
复制相似问题