在列表推导式中调用函数

4
我这里有一个函数。
def celToFah(x):
    ftemps = []
    for i in x:
        ftemps.append((9/5 * i) + 32)
    return ftemps

这里是在列表推导式中调用它。

ctemps = [17, 22, 18, 19]

ftemps = [celToFah(c) for c in ctemps]

遇到以下错误:

“int”对象不可迭代

为什么会出现这个错误?


1
因为您正在将 int 传递给 celToFah。在 celToFah 中,您使用 for 循环迭代传递了 int 的参数 x。您无法迭代 int 对象。这就是错误提示的含义。 - juanpa.arrivillaga
你希望得到什么输出? - Joshua Pierce
1个回答

10

celToFah 函数需要一个列表作为参数,但你传入了一个 int

你可以修改 celToFah 函数,使其也能接受 int 类型的参数:

def celToFah(x):
    return 9/5 * x + 32

ctemps = [17, 22, 18, 19]
ftemps = [celToFah(c) for c in ctemps]

或者直接将ctemps传入celToFah函数:

def celToFah(x):
    ftemps = []
    for i in x:
        ftemps.append((9/5 * i) + 32)
    return ftemps

ctemps = [17, 22, 18, 19]
ftemps = celToFah(ctemps)

谢谢!我没有意识到我正在向函数传递一个整数! - blockByblock

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接