Python如何从包含列表的列表中选择项目
问题描述:
我在生成地图时遇到问题。它使用几个包含向量列表的列表。还有一组墙列表(该列表代表由矢量指向的地方迷宫)。所以我有随机问题。当我从迷宫列表中选择随机项目时。程序会变得疯狂,并创造一些没有多大意义的东西。我试图手动选择每个迷宫,并完美运作。我试图找到解决这个问题的方法,但没有回答这种问题。在这个循环中从迷宫列表中随机选择一个项目是错误的。编辑:这里是可以运行以查看结果的程序。Python如何从包含列表的列表中选择项目
import pygame, random, sys
WIDTH= 640
HEIGHT = 480
WHITE = (255, 255, 255)
BLUE = (50, 50, 255)
clock = pygame.time.Clock()
screen= pygame.display.set_mode((WIDTH, HEIGHT))
screen.fill(WHITE)
wall_list = pygame.sprite.Group()
all_sprite_list = pygame.sprite.Group()
class Wall(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
def ran_map():
walls_1 = [ [0, 0, 40, 20],
[60, 0, 30, 20],
[0, 40, 40, 10],
[60, 40, 30, 10]
]
walls_2 = [ [0, 0, 60, 10],
[40, 10, 20, 10],
[0, 30, 20, 20],
[20, 40, 70, 10],
[80, 0, 10, 40]
]
walls_3 = [ [0, 0, 10, 50],
[10, 0, 80, 10],
[80, 10, 10, 40],
[30, 30, 30, 20]
]
s_maze = [walls_1, walls_2, walls_3]
vectors = [[60, 60], [170, 60], [380, 60], [490, 60], [60, 370], [170, 370], [380, 370], [490, 370]]
for item in vectors:
v1 = item[0]
v2 = item[1]
random_item = random.choice(s_maze)
for item in random_item:
w1 = item[0]
w2 = item[1]
s1 = w1+ v1
s2 = w2+ v2
wall = Wall(s1, s2, item[2], item[3])
wall_list.add(wall)
all_sprite_list.add(wall)
def xz():
done = False
while not done:
pygame.init()
clock.tick(45)
ran_map()
all_sprite_list.draw(screen)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.quit()
def main():
xz()
main()
答
的“要疯了”是最有可能是由于这个重复迭代变量:
for *item* in vectors:
...
for *item* in random_item:
我建议您简化代码的中间部分如下:
...
mazes = { # a dictionary of mazes
'walls_1': [ [0, 0, 40, 20],
[60, 0, 30, 20],
[0, 40, 40, 10],
[60, 40, 30, 10]
],
'walls_2': [ [0, 0, 60, 10],
[40, 10, 20, 10],
[0, 30, 20, 20],
[20, 40, 70, 10],
[80, 0, 10, 40]
],
'walls_3': [ [0, 0, 10, 50],
[10, 0, 80, 10],
[80, 10, 10, 40],
[30, 30, 30, 20]
]
}
vectors = [[60, 60], [170, 60], [380, 60], [490, 60], [60, 370], [170, 370], [380, 370], [490, 370]]
for v1, v2 in vectors:
random_item = random.choice(list(mazes.values()))
for w1, w2, w3, w4 in random_item:
s1 = w1 + v1
s2 = w2 + v2
wall = Wall(s1, s2, w3, w4)
wall_list.add(wall)
all_sprite_list.add(wall)
...
究竟发生不应该发生?如果在完整的堆栈跟踪中发现错误。 – syntonym
你能告诉我你的程序是什么意思,选择一些疯狂的东西吗?你是什么意思手动采摘? –
您正在使用'item'来处理两个不同的事物,它们会破坏第一个值。 – stark