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

如何将列表传入函数?解决Fahrenheit转Celsius的TypeError问题

解决华氏温度列表转摄氏温度的TypeError问题

错误TypeError: unsupported operand type(s) for -: 'list' and 'int'的核心原因是:你的fahrToCelsius函数直接对整个列表执行了数值运算(比如temp - 32),但列表和整数不支持减法操作,必须逐个处理列表里的每个温度值。

tempFahrenheit = tempData没用的原因是:这只是给原列表起了个新名字,本质还是同一个列表对象,函数接收的依然是整个列表,运算逻辑没改,错误自然不会消失。

三种可行的修复方案:

1. 循环遍历逐个转换

修改函数,遍历输入列表的每个元素,计算后收集结果:

def fahrToCelsius(temp_list):
    celsius_list = []
    for temp in temp_list:
        # 对单个温度值执行转换计算
        celsius = (temp - 32) * 5 / 9
        celsius_list.append(celsius)
    return celsius_list

# 调用示例
tempCelsius = fahrToCelsius(tempData)

2. 列表推导式简化写法

用列表推导式一行完成遍历和转换,代码更简洁:

def fahrToCelsius(temp_list):
    return [(temp - 32) * 5 / 9 for temp in temp_list]

# 调用示例
tempCelsius = fahrToCelsius(tempData)

3. 结合map函数使用

如果想保留原函数对单个数值的处理逻辑,可以用map批量处理列表元素:

# 原函数(仅处理单个数值)
def fahrToCelsius(temp):
    return (temp - 32) * 5 / 9

# 用map批量转换,再转成列表
tempCelsius = list(map(fahrToCelsius, tempData))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:02:24