TypeError(“'int'对象不可迭代”,在python 3中的代码中

时间:2021-05-12 20:18:16

I got an assignment in my CS class: to find pairs of numbers in a list, that add to a number n, that is given. This is the code I wrote for it:

我在CS课上有一项作业:在一个列表中找到一对数字,它加上一个数字n,这是已知的。这是我为它写的代码:

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

When I try to run it, I'm given the following message:

当我尝试运行它时,我得到以下信息:

TypeError("'int' object is not iterable",)

What is the problem? I can't find a place in which I use a list obj as an int, or vice versa.

这个问题是什么?我找不到一个地方可以使用obj列表作为int类型,反之亦然。

2 个解决方案

#1


0  

num_list must be iterable.

num_list必须iterable。

Your code return first pair, not all pairs.

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

Read about List Comprehensions

阅读列表理解

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

#2


0  

If you want to use your function like a list, you can yield the values instead of returning them:

如果你想像列表一样使用你的函数,你可以生成值而不是返回值:

def pair (n, num_list):       
    for i in num_list:
        for j in num_list:
            if i + j == n:
                yield i, j

More info here: https://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/

更多信息:https://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/

#1


0  

num_list must be iterable.

num_list必须iterable。

Your code return first pair, not all pairs.

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

Read about List Comprehensions

阅读列表理解

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

#2


0  

If you want to use your function like a list, you can yield the values instead of returning them:

如果你想像列表一样使用你的函数,你可以生成值而不是返回值:

def pair (n, num_list):       
    for i in num_list:
        for j in num_list:
            if i + j == n:
                yield i, j

More info here: https://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/

更多信息:https://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/