我有一個列表,它將一個聯繫人對象的y座標存儲在一個列表中,這樣我就可以訪問聯繫人的相對於其y位置的信息屏幕。如果這是有用的信息,我使用PyGame。Python:IndexError:列表索引超出範圍 - 訪問PyGame對象的y值
打印列表正常,並返回正確的值,但是當我試圖訪問主事件循環中的列表時,我用for
循環迭代列表時出現上述錯誤。
這裏是y值的追加到我的清單代碼:
class MainPage(Page):
...
def printContacts(self):
addressBook = AddressBook()
addressBook.contactsList
addressBook.contactsList.sort(key = lambda c: (c.lastName, c.firstName) if c.lastName else (c.firstName, ""))
contactFont = pygame.font.SysFont("trebuchet ms", 18)
global indexedContacts
indexedContacts = {}
global yIndex
yIndex = [] #List to append y values to
y = 20
for (key, g) in groupby(addressBook.contactsList, lambda c: c.lastName[0] if c.lastName else c.firstName[0]):
groupName = contactFont.render(key, True, (171,0,0))
self.intermediate2.blit(groupName, (5, y))
pygame.draw.line(self.intermediate2, (0,0,0), (5,(y+20)), (320, (y+20)), 1)
y += 30
for i in g:
name = i.firstName + " " + i.lastName
textName = contactFont.render(name, True, (0,0,0))
pygame.draw.line(self.intermediate2, (210,210,210), (5,(y+20)), (320, (y+20)), 1)
self.intermediate2.blit(textName, (5, y))
indexedContacts[(y+72)] = i
yIndex.append((y+72)) #Appends current value to list
y += 30
這裏是一個真實返回錯誤的事件代碼:
for i in yIndex:
if y >= (yIndex[i] - 10) and y <= (yIndex[i] + 20): #Error here
y = yIndex[i]
if y in indexedContacts:
page = EditPage()
page.style()
page.contactFields()
break
else:
continue