【问题标题】:Can somebody help me out in this error if 0<upperpipes[0]['x']<5: KeyError: 0如果 0<upperpipes[0]['x']<5: KeyError: 0 有人可以帮我解决这个错误吗
【发布时间】:2021-05-16 06:45:32
【问题描述】:

这是代码:- 我正面临upperpipes 的问题。要么它无法访问upperpipes 的第一个元素的键,即'x',要么我无法理解。帮我解决这个错误

def mainGame():
    upperpipes=[
        {'x': SCREENWIDTH + 200, 'y': newPipe1[0]['y']},
        {'x': SCREENWIDTH + 200 + (SCREENWIDTH / 2), 'y': newPipe2[0]['y']}
                ]

    lowerpipes = [
        {'x': SCREENWIDTH + 200, 'y': newPipe1[1]['y']},
        {'x': SCREENWIDTH + 200 + (SCREENWIDTH / 2), 'y': newPipe2[1]['y']}
                 ]      
     
        #Add A NEW PIPE WHEN THE fIRST IS ABOUT TO cross THE LEFT MOST PART OF SCREEN
        if 0<upperpipes[0]['x']<5:
            newpipe=getRandomPipe()
            upperpipes.append(newpipe[0])
            lowerpipes.append(newpipe[1])

【问题讨论】:

  • 这不是Minimal, Reproducible Example。在您的应用程序中,初始化和if-语句之间有一些代码代码。很可能有一些代码删除了管道并且列表为空。
  • getRandomPipe() 的代码在哪里? python也不使用CamelCase。

标签: python pygame keyerror


【解决方案1】:

列表似乎是空的。检查列表是否为空:

if 0&lt;upperpipes[0]['x']&lt;5:

if not upperpipes or 0 < upperpipes[0]['x'] < 5:
    # [...]

【讨论】:

    猜你喜欢
    • 2016-07-09
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    相关资源
    最近更新 更多