Python如何通过变量传入多个输入 批量调用函数获取多输出
问题原因
你的代码无法正常输出、批量处理失效的核心原因有两点:
new_variable = "WORD", "AGAIN"实际定义的是元组类型,不是单个字符串。你直接把整个元组传入仅支持单个字符串入参的syllable_count函数时,函数内部执行word.lower()会触发类型错误,部分未开启错误回显的运行环境会直接表现为无输出。- 现有计数函数仅实现了单个单词的统计逻辑,没有做批量遍历处理,无法直接接收多单词的集合类参数完成计算。
修复方案
只需要补充批量遍历逻辑,把每个单词单独传入计数函数即可,不需要改动原有音节计数的核心逻辑:
# 待统计的多个单词统一存在列表中,后续新增单词直接往列表里追加即可 word_list = ["WORD", "AGAIN", "management", "announcement", "mobile"] def syllable_count(word): word = word.lower() count = 0 vowels = "aeiouy" if word[0] in vowels: count += 1 for index in range(1, len(word)): if word[index] in vowels and word[index - 1] not in vowels: count += 1 if word.endswith("e"): count -= 1 if word.endswith("le"): count += 1 if word.endswith("ia"): count += 1 if count == 0: count += 1 if word.endswith("management"): count -= 1 if word.endswith("announcement"): count -= 1 return count # 遍历列表逐个统计,直接打印结果 for word in word_list: print(f"{word} 音节数:{syllable_count(word)}") # 如果需要留存统计结果,可以用字典格式存储 count_result = {word: syllable_count(word) for word in word_list}
运行说明
修复后代码不会再触发类型报错,会逐行输出每个单词的音节数,后续要扩容批量处理的单词量,只需要修改word_list列表的内容即可,不需要调整函数和遍历逻辑。
内容的提问来源于stack exchange,提问作者TVXD
相关产品推荐
相关产品推荐

