我在CS類中得到了一個任務:在列表中找到數字對,並將其添加到數字n,即鑑於 這是我寫它的代碼:TypeError(「'int'object is not iterable」,in my python 3
def pair (n, num_list):
"""
this function return the pairs of numbers that add to the value n.
param: n: the value which the pairs need to add to.
param: num_list: a list of numbers.
return: a list of all the pairs that add to n.
"""
for i in num_list:
for j in num_list:
if i + j == n:
return [i,j]
continue
當我嘗試運行它,我給出了以下消息:
TypeError("'int' object is not iterable",)
有什麼問題我不能找到一個我使用list
obj作爲int
的地方,o反之亦然。
http://stackoverflow.com/questions/1938227/int-object-is-not-iterable –
嗨,我試着你的功能與>>>對(4,[1,2,3]) [ 1,3],它的工作原理是 –
1)。你傳遞一個整數而不是數字列表作爲'pair'的第二個參數。 2)但是,即使你正確地調用它,你的'pair'函數將只返回它找到的第一個對的列表。您需要將這些配對收集到主列表中,並在您測試完每對配對後返回該列表。 3)。您的代碼將測試'num_list'中的數字是否與自身配對,這可能是正確的。但是它測試了其他兩個對,這可能並不正確。 –