简体   繁体   English

IndexError:字符串索引超出范围,当迭代列表的字典时

[英]IndexError: string index out of range, when iterating over dict of lists

I'm sorry if this should be considered a duplicate, I went over several other questions and couldn't locate the mistake because it is probably to special to my case...如果这应该被视为重复,我很抱歉,我查看了其他几个问题,但找不到错误,因为它可能对我的情况很特殊......

I know the problem is somewhere here, I'm using this to draw each char in a dictionary:我知道问题出在这里,我用它来绘制字典中的每个字符:

Edit: Alright, this was to abstract for a concrete example, I don't know where it's going wrong, so I'll post the whole code:编辑:好的,这是一个具体例子的抽象,我不知道哪里出了问题,所以我将发布整个代码:

import pygame, random, time, sys, string, itertools

check_errors = pygame.init()

################### Main Variables ######################

PSwith = 460
PSheight = 460
playSurface = pygame.display.set_mode((PSwith, PSheight))

rowsCount = int(PSwith/10 - 1)
columnsCount = int(PSheight/10 - 1)

print('rows: ', rowsCount)
print('columns: ', columnsCount)

alphabet = list(string.ascii_letters + string.punctuation + string.digits)

red = pygame.Color(255,0,0)
blue = pygame.Color(0,0,255)
green = pygame.Color(0,255,0)
white = pygame.Color(255,255,255)
black = pygame.Color(0,0,0)

defaultColor = green
activeColor = white

fpsController = pygame.time.Clock()

################### Important Functions ######################

def drawChar(char, x, y, color):
    CharFont = pygame.font.SysFont('hermit', 15)
    CharSurf = CharFont.render(char, True, color)
    CharRect = CharSurf.get_rect()
    CharRect.midtop = (x, y)
    playSurface.blit(CharSurf, CharRect)

CharPosMatrix = []
CharLibrary = []

def setCharPos(row):
    for column in range(1, int(PSwith/10)):
        CharPosMatrix.append((column*10, row*10))

for row in range(1, int(PSheight/10)):
    setCharPos(row)

print('CharPosMatrix: ', CharPosMatrix)
print('len CharPosMatrix:', len(CharPosMatrix))


### assembling char library, with default color ###
for i in range(rowsCount * columnsCount):
        CharLibrary.append([random.choice(alphabet), defaultColor])

print('CharLibrary: ', CharLibrary)
print('len CharLibrary:', len(CharLibrary))

#MatrixDict = dict(zip(CharLibrary, CharPosMatrix))
MatrixDict = dict(zip(CharPosMatrix,CharLibrary)) #zipping each character with a x,y coord
print('MatrixDict: ', MatrixDict)
print('len MatrixDict: ', len(MatrixDict))

################### Main Loop ######################

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    playSurface.fill(black)

    holderlist = []
    indexCounter = 0


    for key, value in MatrixDict.items():
        drawChar(value[0], key[0], key[1], value[1])
        print(key)
        print(value)

    ### start changing random elements ###

    n = 0
    for i in range(random.randint(1, 200)):
        MatrixDict[random.choice(CharPosMatrix)]= random.choice(alphabet)
        n += 1
    print('randomly changed characters: ', n)

    randColumn = 0
    for i in range(10):
        MatrixDict[(10, 10)] = 'X'

    pygame.display.flip()

    fpsController.tick(60) 

the part where I actually know, the error spawns is:我真正知道的部分,错误产生的是:

        for key, value in MatrixDict.items():
            drawChar(value[0], key[0], key[1], value[1])
            print(key)
            print(value) 

if I change value[1] to the variable green ie, the code runs...如果我将 value[1] 更改为变量 green,即代码运行...

You have set up MatrixDict correctly in the beginning, and everything works correctly the first time main while-loop is iterated.您已经在开始时正确设置了 MatrixDict,并且在第一次迭代主 while 循环时一切正常。 In the end of the while-loop however there are two lines where you modify MatrixDict, which breaks the code for future iterations:然而,在 while 循环的末尾有两行修改 MatrixDict,这会破坏未来迭代的代码:

88: MatrixDict[random.choice(CharPosMatrix)] = random.choice(alphabet)
94: MatrixDict[(10, 10)] = 'X'

In both cases, you need to specify color as well as character, eg:在这两种情况下,您都需要指定颜色和字符,例如:

88: MatrixDict[random.choice(CharPosMatrix)] = random.choice(alphabet), defaultColor
94: MatrixDict[(10, 10)] = 'X', defaultColor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM