【问题标题】:Call function in List Comprehension列表理解中的调用函数
【发布时间】:2019-02-27 01:28:51
【问题描述】:

这里有一个函数

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

为什么我会收到错误消息?

【问题讨论】:

  • 因为您将int 传递给celToFah。在celToFah 中,您使用for 循环(已传递int 的那个)遍历参数x。您不能迭代 int 对象。这就是错误告诉你的内容。
  • 你希望得到什么输出?

标签: python python-3.x function list-comprehension


【解决方案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)

【讨论】:

  • 谢谢!我不知道我正在将一个 int 传递给函数!
猜你喜欢
  • 1970-01-01
  • 2019-03-23
  • 2017-03-10
  • 2021-03-24
  • 2012-11-12
  • 1970-01-01
  • 2019-06-20
  • 2018-09-21
  • 2018-04-12
相关资源
最近更新 更多