Python 为什么try-except块没有捕获索引器?

Python 为什么try-except块没有捕获索引器?,python,Python,我有以下功能: def get_prev_match_elos(player_id, prev_matches): try: last_match = prev_matches[-1] return last_match, player_id except IndexError: return 有时prev\u matches可能是一个空列表,因此我添加了try-except块来捕获索引器。然而,当我传递一个空列表而不是excep

我有以下功能:

def get_prev_match_elos(player_id, prev_matches):
    try:
        last_match = prev_matches[-1]
        return last_match, player_id
    except IndexError:
        return
有时
prev\u matches
可能是一个空列表,因此我添加了try-except块来捕获
索引器。然而,当我传递一个空列表而不是except块时,我仍然在
last\u match=prev\u matches[-1]
上得到一个显式的
索引器

我尝试在另一个文件中复制此函数,效果很好!有什么想法吗

完全错误:

Exception has occurred: IndexError
list index out of range
  File "C:\Users\Philip\OneDrive\Betting\Capra\Tennis\polgara\elo.py", line 145, in get_prev_match_elos
    last_match = prev_matches[-1]
  File "C:\Users\Philip\OneDrive\Betting\Capra\Tennis\polgara\elo.py", line 24, in engineer_elos
    get_prev_match_elos(player_id, prev_matches_all_surface)
  File "C:\Users\Philip\OneDrive\Betting\Capra\Tennis\polgara\updater.py", line 499, in engineer_variables
    engineer_elos(dal, p1_id, date, surface, params)
  File "C:\Users\Philip\OneDrive\Betting\Capra\Tennis\polgara\updater.py", line 99, in run_updater
    engineer_variables(dal, matches_for_engineering, params)
  File "C:\Users\Philip\OneDrive\Betting\Capra\Tennis\polgara\decorators.py", line 12, in wrapper_timer
    value = func(*args, **kwargs)
  File "C:\Users\Philip\OneDrive\Betting\Capra\Tennis\polgara\updater.py", line 72, in main
    run_updater(dal, scraper)
  File "C:\Users\Philip\OneDrive\Betting\Capra\Tennis\polgara\updater.py", line 645, in <module>
    main()
发生异常:索引器错误
列表索引超出范围
文件“C:\Users\Philip\OneDrive\Botting\Capra\Tennis\polgara\elo.py”,第145行,在get\u prev\u match\u elos中
上次匹配=上次匹配[-1]
文件“C:\Users\Philip\OneDrive\Botting\Capra\Tennis\polgara\elo.py”,第24行,在engineer\u elos中
获取上一个匹配(玩家id,上一个匹配所有表面)
文件“C:\Users\Philip\OneDrive\Botting\Capra\Tennis\polgara\updater.py”,第499行,工程师变量
工程师(dal、p1、id、日期、表面、参数)
文件“C:\Users\Philip\OneDrive\Botting\Capra\Tennis\polgara\updater.py”,第99行,运行更新程序
工程师变量(dal、与工程师匹配的变量、参数)
文件“C:\Users\Philip\OneDrive\Botting\Capra\Tennis\polgara\decorators.py”,第12行,包装器计时器
值=func(*args,**kwargs)
文件“C:\Users\Philip\OneDrive\Botting\Capra\Tennis\polgara\updater.py”,第72行,主目录
运行更新程序(dal、刮板)
文件“C:\Users\Philip\OneDrive\Botting\Capra\Tennis\polgara\updater.py”,第645行,在
main()

我也无法复制错误,但一个简单的解决方法是不以这种方式使用异常。编程语言没有针对经常手动处理异常进行优化。它们只应用于抢先捕获可能的故障,而不是用于正常逻辑。尝试检查它是否为空

def get_prev_match_elos(player_id, prev_matches):
    if not prev_matches:
        return

    last_match = prev_matches[-1]
    return last_match, player_id

,使用C#作为语言:

请显示错误堆栈跟踪,好像它在其他地方抛出。如果len(prev_matches)==0:return
,为什么不执行
?这很奇怪,你确定保存了新代码吗。。?这是我能得到的唯一解释。或者,您在执行另一个文件时正在处理该文件的副本?
try/except
应用于异常和意外情况。您可以轻松检查的常见情况应该明确检查。不要担心性能,除非它成为瓶颈。我不同意。Python甚至有一个使用try/exception编码风格的首字母缩略词。EAFP。甚至python中的迭代也会通过抛出StopIteration异常来停止。适用于其他语言的内容不一定适用于Python