List Finrehension中的调用函数

问题描述 投票:1回答:1

我在这里有一个功能

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'对象不可迭代

为什么我收到错误?

python python-3.x function list-comprehension
1个回答
1
投票

celToFah期待一个名单,你给它一个int

要么改变celToFah只是在ints上工作,就像这样:

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)
© www.soinside.com 2019 - 2024. All rights reserved.