【问题标题】:Why index eror occurr in this case and how to fix it在这种情况下为什么会发生索引错误以及如何修复它
【发布时间】:2021-12-02 13:15:06
【问题描述】:

问题是:编写一个函数 [D,P,F]=formalConvert(S) 来提取 D 和 P,然后将练习 1.excluded (f) 中的语句 S 转换为正式形式 F。

提示:D包含For all/Exist/There is at least one和一个逗号(,)之间的词; P 包含逗号 (,) 中第一个单词之后的单词。

这是我的代码(python)

S = ['For all fishes, they need water to survive',
     'Exist a person, who is left handed',
     'Exist an employee in the company, who is late to work everyday',
     'For all fishes in this pond, they are Koi fish',
     'There is at least one creature in the ocean, it can live on land',
     'Every students in class A did not pass the test'
     ]
A = ['For all ', 'Exist a ','Exist an ', 'There is at least one ']
def formalConvert(S):
    F = 'Formal form : For all x in D, P(x)'
    arr = S.split(', ')
    for a in A:
        if (arr[0].find(a)!=-1):
        
            D = arr[0].replace(a,'')
            P = ' '.join(arr[1].split()[1:])
        else:
            arr1 = s.split(' did not ')
            D = arr1[0].replace('Every ','')
            P = arr1[1].replace('pass','did not pass')
        return [D, P, F]
for s in S:
    print(formalConvert(s))

当我运行它时发生错误:

  Traceback (most recent call last):
  File "d:\lab3\ex2.py", line 26, in <module>     
    print(formalConvert(s))
  File "d:\lab3\ex2.py", line 20, in formalConvert
    P = arr1[1].replace('pass','did not pass')    
IndexError: list index out of range

【问题讨论】:

  • 请清楚地格式化您的代码和问题
  • arr1 将仅包含 1 个元素,如果 s 不包含 ´ did not' 。所以访问第二个元素是不正确的。

标签: python indexing compiler-errors discrete-mathematics index-error


【解决方案1】:

在 else 语句中,您使用“did not”进行拆分,但是,列表中的大多数字符串都没有“did not”。所以s.split(' did not ') 的结果不是两个元素,而是一个。因此,如果您尝试访问“1”元素(第 2 个),您的数组就会超出范围。

只是一个友好的提示,尝试熟悉调试器,我向你保证,这会很有帮助。

【讨论】:

    猜你喜欢
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多