2015-11-07 82 views
-1

我在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反之亦然。

+0

http://stackoverflow.com/questions/1938227/int-object-is-not-iterable –

+0

嗨,我试着你的功能与>>>对(4,[1,2,3]) [ 1,3],它的工作原理是 –

+0

1)。你传递一个整数而不是数字列表作为'pair'的第二个参数。 2)但是,即使你正确地调用它,你的'pair'函数将只返回它找到的第一个对的列表。您需要将这些配对收集到主列表中,并在您测试完每对配对后返回该列表。 3)。您的代码将测试'num_list'中的数字是否与自身配对,这可能是正确的。但是它测试了其他两个对,这可能并不正确。 –

回答

0

num_list必须是可迭代的。

你的代码返回第一对,而不是所有的对。

阅读有关List Comprehensions

[[i, j] for i in num_list for j in num_list if i + j == n]