You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python循环,在替换字典切换时插入CHANGE字符串

解决代码

words_input = "Duck Bear Bear Duck Duck Bear Bear Bear Bear Duck Bear Bear Duck Duck"

replacements = [{'Bear': ["Black", "Woods"], 'Duck': ["Bird", "Feathers"]},
                {'Bear': ["Grizzly", "Woods"], 'Duck': ["Quack", "Feathers"]},
                {'Bear': ["Grizzly", "Black"], 'Duck': ["Quack", "Bird"]}]

output = []
index_replace = 0
count_replace = {key: 0 for key in replacements[0].keys()}
for word in words_input.split():
    if count_replace[word] == len(replacements[index_replace][word]):
        # 切换替换字典
        index_replace = (index_replace + 1) % len(replacements)
        count_replace = {key: 0 for key in replacements[0].keys()}
        # 新增:切换后插入CHANGE标记
        output.append("CHANGE")
    idx_word = count_replace[word]
    output.append(replacements[index_replace][word][idx_word])
    count_replace[word] += 1

output_words = ' '.join(output)
print(output_words)

运行后输出结果和要求完全一致:
Bird Black Woods Feathers CHANGE Quack Grizzly Woods CHANGE Grizzly Black Quack CHANGE Black Woods Bird Feathers


内容的提问来源于stack exchange,提问作者user17026080

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:36:07