简体   繁体   中英

Call function in List Comprehension

Here I have a function

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

where I call it in the list comprehension.

ctemps = [17, 22, 18, 19]

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

getting the following error

'int' object is not iterable

Why am I getting the error?

celToFah is expecting a list, you are giving it an int .

Either change celToFah to just work on int s like so:

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

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

Or pass ctemps directly into 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM