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

标签 python 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 模块/方法?

最佳答案

这只是列表的笛卡尔积

import itertools

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

或者你可以直接从你的字典@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

关于用于生成字符串中可能的字符串替换的所有排列的 Python 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24634833/

相关文章:

java - 如何实现一种算法来检查 Python 代码的缩进

python - 在 Mako 中编码 JSON?

python 3 : What is the most efficient way to calculate all permutations of two lists summing to 100?

python itertools 产品慢是输出文件的写入速度的瓶颈

python - sqlalchemy 中插入操作的列名和类型

python - Django OAuth 工具包 "resource-owner password based"授权类型

python - 无法在带有 GPU 的 tensorflow 教程中运行词嵌入示例

python - 成员每组出现一次的唯一对组

python - 为什么 dropwhile 和 takewhile 会跳过最后一个 a?

python - 如何存储 itertools.chain 并多次使用它?