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

如何将两个列表作为函数参数实现批量调用?

解决方案

你的问题出在直接把整个列表作为参数传给make_tshirt函数,但这个函数是为处理单个尺码和文本设计的,没法直接批量处理列表元素。要实现遍历两个列表、逐个传入对应参数的效果,按以下方式修改代码:

修改后的完整代码

def make_tshirt(size, text='I love Python!'):
    # 统一将尺码转为大写,避免大小写匹配问题
    size = size.upper()
    v = []
    if len(text) <= 20:
        v = ['S', 'M', 'L']
    elif len(text) <= 30:
        v = ['M', 'L']
    elif len(text) <= 50:
        v = ['L']
    else:
        v = []

    if text == '':
        text = 'I love Python!'

    if size in v:
        print(f"You ordered a {size} tshirt with the text '{text}'.")
    else:
        print("The size you want don't have enough space to your text.")

sizes = ['m', 's', 'l', 's']
texts = ['I like Python', 'Am I a robot?', 'Weird Year', 'God, Our savior']

# 用zip配对两个列表的对应元素,循环调用函数
for size, text in zip(sizes, texts):
    make_tshirt(size, text)

核心修改说明

  • 使用zip(sizes, texts)将两个列表的对应元素一一配对,每次循环取出一组(尺码, 文本)数据。
  • 在函数内部添加size = size.upper(),确保传入的小写尺码自动转为大写,避免和v列表中的大写尺码不匹配。
  • 替换原有的单次函数调用为循环调用,让每一组对应元素都触发一次函数执行,从而得到四次输出结果。

运行修改后的代码,会输出你期望的内容:

You ordered a M tshirt with the text 'I like Python'.    
You ordered a S tshirt with the text 'Am I a robot?'.    
You ordered a L tshirt with the text 'Weird Year'.    
You ordered a S tshirt with the text 'God, Our savior'.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:10:32