def scan_for_match(T1, T2):
i = 0
j = 0
while i <= (len(T1)):
if T1[i] == T2[j]:
keywords = open('keywords.txt', 'w+')
keywords.write(T1.pop(i))
T2.pop(j)
if i > (len(T1)):
i = 0
j += 1
if j > (len(T2)):
print "All words have been scanned through"
print "These are the matches found:\n ", keywords.readlines()
i += 1
我认为这是一段相当简单的代码,但是......
T1 = ["me", "gusta", "espanol"]; T2 = ["si", "no", "espanol"]; scan_for_match(T1, T2)
请给我:
Traceback (most recent call last):
File "stdin", line 1, in module
File "stdin", line 5, in scan_for_match
IndexError: list index out of range
有问题的行只是无害if T1[i] == T2[j]:
从那以后,对我来说没有意义:
i = 0
j = 0
T1[i] = 'me'
T2[j] = 'si'
所以这应该只返回一个False结果而不是一个IndexError,对吗?
答案 0 :(得分:2)
while i <= (len(T1)):
错误,当我等于长度时,它会有IndexError,将其更改为<
。索引从 0 开始到(length - 1)
我建议不要使用pop()
方法,它会从列表中删除元素,扫描匹配并不需要删除匹配元素,对吧? :)
或者,您可以通过以下方式找到匹配项:
>>> t2= ["si", "no", "espanol"]
>>> t1= ["me", "gusta", "espanol"]
>>> set(t2) & set(t1)
{'espanol'}
答案 1 :(得分:1)
将logs
上的条件更改为:
while
当while i < len(T1)
# ^
并且您尝试索引列表时,您将获得i = len(T1)
,因为您的索引从零开始计数。