【问题标题】:TypeError: 'int' object is not iterable in map functionTypeError:'int'对象在地图函数中不可迭代
【发布时间】:2018-04-26 14:31:01
【问题描述】:

对不起,我是新手 python 编码器。 我在 PyCharm 中编写了这段代码:

lst_3 = [1, 2, 3]

def square(lst):
    lst_1 = list()
    for n in lst:
        lst_1.append(n**2)

    return lst_1


print(list(map(square,lst_3)))

我有这种类型的错误:TypeError: 'int' object is not iterable。 我的代码有什么错误?

【问题讨论】:

  • 我看到你发布的代码有一个奇怪的缩进,你能解决这个问题吗?
  • map 有一个对每个元素进行操作的函数——在你的例子中是一个标量。
  • 当您将map square 转为lst_3 时,每个数字依次传递给square。您无需对数字进行迭代
  • 你可以做list(map(lambda x: x**2, lst_3))

标签: python python-3.x typeerror


【解决方案1】:

这里的问题是您对 map 所做的事情的误解。这是一个有代表性的例子。我创建了一个“身份”函数,它只是回显一个数字并返回它。我将map这个函数添加到一个列表中,这样你就可以看到打印出来的内容了:

In [382]: def foo(x):
     ...:     print('In foo: {}'.format(x))
     ...:     return x
     ...: 

In [386]: list(map(foo, [1, 2, 3]))
In foo: 1
In foo: 2
In foo: 3
Out[386]: [1, 2, 3]

请注意,列表中的每个元素 都由map 传递给foo foo 没有收到列表。您的错误是认为确实如此,因此您尝试遍历 number 导致您看到的错误。

你需要做的是像这样定义square

In [387]: def square(x):
     ...:     return x ** 2
     ...: 

In [388]: list(map(square, [1, 2, 3]))
Out[388]: [1, 4, 9]

square 应该在它接收标量的假设下工作。

或者,您可以使用lambda 来达到同样的效果:

In [389]: list(map(lambda x: x ** 2, [1, 2, 3]))
Out[389]: [1, 4, 9]

请记住,这是函数式编程的方法。作为参考,使用列表推导会更便宜:

In [390]: [x ** 2 for x in [1, 2, 3]]
Out[390]: [1, 4, 9]

【讨论】:

    猜你喜欢
    • 2017-09-11
    • 1970-01-01
    • 2023-01-22
    • 2020-06-10
    • 2015-12-03
    • 1970-01-01
    • 2018-09-29
    • 2020-02-26
    相关资源
    最近更新 更多