2017-10-10 138 views
0

通过有关该问题的帖子去了,但没有帮助我理解这个问题或解决问题:'int'对象不可迭代python3?

# This is the definition of the square() function 
def square(lst1): 
    lst2 = [] 
    for num in lst1: 
     lst2.append(num**2) 
    return lst2 

n = [4,3,2,1] 

print(list(map(square, n))) 
>>> 
File "test.py", line 5, in square 
    for num in lst1: 
TypeError: 'int' object is not iterable 

什么是错的square()功能定义,行,该如何解决? 非常感谢!

+0

[编辑]你的问题,不要在评论中填写。 –

+0

现在“方形”太复杂了。 'map'一次传递一个整数。你需要'def square(n):return n * n' –

+0

你不需要在你的函数中为'lst1'中的num。该功能一次只收到一个列表元素。只要'返回lst1 ** 2';返回一次性列表通常无用 – WillardSolutions

回答

0

mapsquare应用于您的列表中的每个项目。

因此在square中包含循环是多余的。当函数被调用时,lst1已经是一个整数。

要么是:

result = square(n) 

或:

result = [i*i for i in n] 

后者更好&快于

result = list(map(square,n)) 

有:

def square(i): 
    return i*i 

(或lambda

+0

谢谢! 我只专注于使用带有自定义函数的'map()'作为第一个参数。此时我不想混入更多花哨的东西。 – Yifangt

相关问题