【问题标题】:IndexError Exception in PythonPython中的IndexError异常
【发布时间】:2019-11-28 18:10:02
【问题描述】:

下面,我们提供了一个元组列表,其中包含学生姓名、期末考试成绩以及他们是否会通过课程。对于一些学生来说,元组没有第三个元素,因为不知道他们是否会通过。目前,for 循环不起作用。添加一个 try/except 子句,以便代码运行时不会出错 - 如果元组中没有第三个元素,则不应对字典进行任何更改。

students = [('Timmy', 95, 'Will pass'), ('Martha', 70), ('Betty', 82, 'Will pass'), ('Stewart', 50, 
          'Will not pass'), ('Ashley', 68), ('Natalie', 99, 'Will pass'), ('Archie', 71), ('Carl', 
           45, 'Will not pass')]

passing = {'Will pass': 0, 'Will not pass': 0}

for tup in students:
 if tup[2] == 'Will pass':
     passing['Will pass'] += 1
 elif tup[2] == 'Will not pass':
     passing['Will not pass'] += 1

如果上面的代码运行,它会给出错误:IndexError: tuple index out of range on line 8 在 try/except 之后,它应该给出 {'Will pass': 3, 'Will not pass':2}

我的尝试是:

try:
    for tup in students:
       if tup[2] == 'Will pass':
           passing['Will pass'] += 1
       elif tup[2] == 'Will not pass':
           passing['Will not pass'] += 1
except Exception, e:
    print("Continue")

它给出{‘会通过’: 1, ‘不会通过’:0}

有人可以告诉我的尝试/例外有什么问题吗?我尝试添加两个 try/except,但仍然得到相同的输出。

【问题讨论】:

  • print("Continue") 不继续循环;它打印"Continue"
  • 您可能希望将try-except 带入循环并使用continue
  • ...并且还捕获 IndexError 而不是 Exception 因为您知道这是您要得到的错误

标签: python exception


【解决方案1】:

您可以明确检查长度为 3 的元组。试试这个:

for tup in students:
    if len(tup)==3:
        if tup[2] == 'Will pass':
            passing['Will pass'] += 1
        elif tup[2] == 'Will not pass':
            passing['Will not pass'] += 1

如果你坚持使用try-except 块,试试这个:

for tup in students:
    try:
        if tup[2]=='Will pass':
            passing['Will pass'] += 1
        elif tup[2]=='Will not pass':
            passing['Will not pass'] += 1
    except:
        pass

输出

passing = {'Will pass': 3, 'Will not pass': 2}

【讨论】:

    【解决方案2】:

    您应该通过检查元组长度来使您的代码更加健壮: 元组长度检查中的消息假设您使用python 3.5+,您可以使用print("Don't know yet if {name} will pass".format(name=tup[0])

    students = [('Timmy', 95, 'Will pass'), ('Martha', 70), ('Betty', 82, 'Will pass'), ('Stewart', 50, 
              'Will not pass'), ('Ashley', 68), ('Natalie', 99, 'Will pass'), ('Archie', 71), ('Carl', 
               45, 'Will not pass')]
    
    passing = {'Will pass': 0, 'Will not pass': 0}
    
    for tup in students:
     if len(tuple) == 2:
       print(f"Don't know yet if {tup[0]} will pass")
       continue
     if tup[2] == 'Will pass':
         passing['Will pass'] += 1
     elif tup[2] == 'Will not pass':
         passing['Will not pass'] += 1
    

    【讨论】:

    • 如果您使用第二个if 作为elif,则可以避免continue
    • 我在循环中使用了两个 try/except,得到了 {‘Will pass’: 2, ‘Will not pass’:1},仍在研究解决方案。
    【解决方案3】:

    这是正确的解决方案

    students = [('Timmy', 95, 'Will pass'), ('Martha', 70), ('Betty', 82, 'Will pass'), ('Stewart', 50, 'Will not pass'), ('Ashley', 68), ('Natalie', 99, 'Will pass'), ('Archie', 71), ('Carl', 45, 'Will not pass')]
    
    passing = {'Will pass': 0, 'Will not pass': 0}
    
    for tup in students:
        try:
            if tup[2] == 'Will pass':
                passing['Will pass'] += 1
            elif tup[2] == 'Will not pass':
                passing['Will not pass'] += 1
        except IndexError:
            continue
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多