python - Python 上的不清楚索引错误

标签 python python-2.7 runtime-error

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,对吗?

最佳答案

while i <= (len(T1)):错了,当i等于长度时,会出现IndexError,改成< 。索引从0开始到(长度 - 1)

我建议不要使用pop()方法,它将从列表中删除元素,扫描匹配不需要删除匹配的元素,对吧? :)

或者,您可以通过以下方式找到匹配项:

>>> t2= ["si", "no", "espanol"]
>>> t1=  ["me", "gusta", "espanol"]
>>> set(t2) & set(t1)
{'espanol'}

关于python - Python 上的不清楚索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38492045/

相关文章:

Python Twitter API Twitter错误: user_id must be type int

python - 如果我在长度为 1 的 QuerySet 上使用 first() 与 last(),为什么会得到不同的结果

python-2.7 - flask :ImportError:没有名为 flask.ext.login 的模块

Android 应用内结算错误 InvalidKeySpecException

python - Django - url 中的 View 或条件根据参数是否具有值或为 NONE 选择两种 url 模式之一

python - python内置函数的源代码

python - cv2.drawContours 没有显示正确的颜色

python - 是否可以将 Python 解释器的状态保存到文件中?

android - libGDX 中的运行时错误

java - 尝试发送电子邮件时出现奇怪的错误