【发布时间】: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