2017-10-10 96 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