【问题标题】:Unclear IndexError on Python [duplicate]Python上的索引错误不清楚[重复]
【发布时间】:2026-02-20 12:15:01
【问题描述】:
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,对吧?

【问题讨论】:

    标签: python python-2.7 runtime-error


    【解决方案1】:

    while i &lt;= (len(T1)):是错误的,当i等于长度时会出现IndexError,改成&lt;。索引从 0(length - 1)

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

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

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

    【讨论】:

    • 感谢您的回答
    • @CaioFleury 我建议不要使用pop() 方法。它将从列表中删除元素
    【解决方案2】:

    while 上的条件更改为:

    while i < len(T1)
    #       ^
    

    i = len(T1) 并且您尝试为列表编制索引时,您将获得IndexError,因为您的索引从零开始计数。

    【讨论】:

    • 感谢您的回答