【问题标题】:TypeError("'int' object is not iterable", in my code in python 3TypeError(“'int'对象不可迭代”,在我的python 3代码中
【发布时间】:2016-02-08 17:11:54
【问题描述】:

我在我的 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

当我尝试运行它时,我收到以下消息:

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

有什么问题?我找不到将list obj 用作int 的地方,反之亦然。

【问题讨论】:

  • 嗨,我用 >>> pair(4, [1,2,3]) [1, 3] 尝试了你的函数,它可以工作
  • 1)。您将传递一个整数而不是数字列表作为pair 的第二个参数。 2) 但即使您 确实 正确调用它,您的 pair 函数也只会返回它找到的第一对的列表。您需要将这些对收集到一个主列表中,并在测试完每一对后返回该列表。 3)。您的代码将测试num_list 中的数字是否与自身配对,这可能没问题。但它每隔一对测试两次,这可能不行。

标签: python python-3.x int typeerror iterable


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    num_list 必须是可迭代的。

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

    了解List Comprehensions

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

    【讨论】:

      猜你喜欢
      • 2015-04-06
      • 2013-10-31
      • 2018-06-21
      • 2016-02-24
      • 1970-01-01
      • 2019-01-12
      • 2017-09-11
      相关资源
      最近更新 更多