我需要循环遍历keys数组,它是一个数组中的一组数组,我使用两个for循环。一种用于访问不同的数组,另一种用于循环访问每个数组的内容。当我到达"for j in range(5):"
时,这是第二个循环,它显示 "AttributeError: 'str' object has no attribute 'length'"
,尽管它不是一个完整的字符串,而是数组中的单独字符,您可以在"keys."
中查看它。循环遍历键数组中所有内容的正确方法是什么?
# import pygame
import os, sys
import pygame
from pygame.locals import *
# initialize game engine
pygame.init()
#WINDOw
width=600
height=400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("keyboard")
filler = 0;
keys = [['a','b','c','d','e','f'],['g','h','i','j''k'],['l','m','n','o','p'],['q','r','s','t','u'],['v','w','x','y','z']];
animation_increment=10
fps=20
dead=False
clock = pygame.time.Clock()
x = 0
class keyBoard(pygame.sprite.Sprite):
#code
def keyDraw(self):
for i in range(5):
for j in keys[i]:
pygame.draw.rect(screen,(255,0,255),(60*i + 10,60*j, 50,50));
最佳答案
列表的长度可以通过len
获取。列表中的列表可以通过以下方式遍历:
for i in range(len(keys)):
for j in range(len(keys[i])):
另一个选择是使用 enumerate
:
for i, keylist in enumerate(keys):
for j, letter in enumerate(keylist):
关于python - 如何在Python中循环遍历另一个数组内的一个数组的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59793095/