我想创建一个函数来生成全名的所有组合,其中替代个人名称的所有变体都被替换。
以下内容帮助我实现了这一目标:
ALT_NAMES = {
"Anthony": ["Tony", "Ant"],
"Christopher": ["Chris"],
}
def generate_alt_names(name: str):
yield name
names = name.split()
for idx, single_name in enumerate(names):
alt_names = ALT_NAMES.get(single_name, [])
for alt_name in alt_names:
yield " ".join(names[:idx] + [alt_name] + names[idx + 1 :])
def main():
print(list(generate_alt_names("Anthony Christopher Clark")))
if __name__ == "__main__":
main()
它输出:
[
"Anthony Christopher Clark",
"Tony Christopher Clark",
"Ant Christopher Clark",
"Anthony Chris Clark",
]
但是,这缺少多个单独名称已被替换的组合:
[
"Tony Chris Clark",
"Ant Chris Clark",
]
我认为答案在于
itertools
函数或某种递归之一,但我正在努力想出解决方案。有人能让我走上正轨吗?
你好乔西,问题是 您原来的代码是它一次只处理替换一个名称。具体来说,您的代码通过替换一个名称来生成变体,然后立即产生结果,而没有考虑其他名称也可能有需要组合替换的替代方案。
这是您任务的正确代码
import itertools
ALT_NAMES = {
"Anthony": ["Tony", "Ant"],
"Christopher": ["Chris"],
}
def generate_alt_names(name: str):
names = name.split()
all_name_variants = []
for single_name in names:
variants = [single_name] + ALT_NAMES.get(single_name, [])
all_name_variants.append(variants)
for combination in itertools.product(*all_name_variants):
yield " ".join(combination)
def main():
print(list(generate_alt_names("Anthony Christopher Clark")))
if __name__ == "__main__":
main()
输出是这样的
['Anthony Christopher Clark', 'Anthony Chris Clark', 'Tony Christopher Clark', 'Tony Chris Clark', 'Ant Christopher Clark', 'Ant Chris Clark']