如何修改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
相关产品推荐
相关产品推荐

