嗨,我对这段代码有错误,我无法看到它来自哪里。有什么想法吗?
def collision2(tab1,tab2):
for i in range(len(tab1)):
for j in range(len(tab2)):
if (tab1[i]==tab2[j]):
return i,j
return -1
答案 0 :(得分:6)
我怀疑,问题在于如何返回并解释函数的结果。如果匹配,则该函数返回一个元组,但如果不是-1
。您可能解压缩函数的结果,如果没有匹配,则会出现此错误:
>>> def collision2(tab1,tab2):
... for i in range(len(tab1)):
... for j in range(len(tab2)):
... if (tab1[i]==tab2[j]):
... return i,j
... return -1
...
>>> x, y = collision2([1, 2, 3], [3, 4, 5]) # there is a match, no error
>>> x, y = collision2([1, 2, 3], [10, 10, 10]) # now, there is no match
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
解决此问题的一种方法是返回-1, -1
元组而不只是-1
:
def collision2(tab1,tab2):
for i in range(len(tab1)):
for j in range(len(tab2)):
if (tab1[i] == tab2[j]):
return i,j
return -1, -1
答案 1 :(得分:0)
您目前看到的错误是元组解包错误,如果 tab1 和 tab2 中没有常见元素,则只返回 -1 因此,当你所有的功能为:
x, y = collision2([1, 2, 3], [4, 5, 6])
y 未分配值,导致引发异常
因此你可以实现这样的功能:
def collision2(tab1, tab2):
for idx1, val1 in enumerate(tab1):
for idx2, val2 in enumerate(tab2):
if val1 == val2:
return idx1, idx2
return -1, -1
有两点需要注意:
enumerate(iterable)
返回iterable的索引处的索引和值。这种做法被认为是pythonic。希望这有帮助。