简体   繁体   English

从Python中的列表访问元组

[英]Accessing tuples from a list in Python

So, I haven't been able to figure out how to do this yet. 因此,我还无法弄清楚该如何做。 I'm making a map parser for a game, and so far I have a three dimensional list "mapData" in the module "maps". 我正在为游戏制作地图解析器,到目前为止,我在模块“地图”中有一个三维列表“ mapData”。 It stores tuples that contain the tile and floor ids. 它存储包含图块和地板ID的元组。 So, when I'm trying to draw the floor, I call 因此,当我尝试打底时,我打电话

if maps.mapData[mapIndex][x][y][0] == 0: c.blit(maps.grass, tileRect)

to draw the grass for example, and to draw the tiles I call 例如画草,画我叫的瓷砖

if maps.mapData[mapIndex][x][y][1] == 1: c.blit(maps.tallGrass, tileRect)

to draw the tall grass. 画高草。 Though, the [0] and [1] is what I'm confused about. 尽管[0]和[1]是我感到困惑的地方。 They are trying to reference the first and second element of the tuple respectively, but I suspect I am doing that wrong, as I am getting this error: 他们试图分别引用元组的第一个和第二个元素,但是我怀疑我做错了,因为我得到了这个错误:

TypeError: 'int' object is not subscriptable

Just to help, the list "mapData" is initialized as follows: 只是为了帮助,列表“ mapData”的初始化如下:

mapData = [[[0 for y in range(19)] for x in range(25)] for m in range(mapAmount)]
mapData[mapIndex["spawn"]][5][5] = (0, 1)

with "mapIndex" being a dictionary of integers that specify what map is what. 其中“ mapIndex”是一个整数字典,用于指定什么地图。

So, I need to know how to get a specific element from a tuple, preferably without using x, y = tuple because that takes a bit more memory, as it has to store the variable. 因此,我需要知道如何从元组中获取特定元素,最好不使用x,y =元组,因为这需要更多的内存,因为它必须存储变量。 and this is in the rendering loop. 这是在渲染循环中。 If that is the only way to do it, then that is ok by me though. 如果那是唯一的方法,那我还是可以的。 Thanks! 谢谢!

As a side question, does anyone have better idea of deciding what tile to draw other than making a giant if+elif statement in the rendering code? 作为附带的问题,除了在渲染代码中编写巨型if + elif语句之外,还有谁能更好地决定要绘制哪个图块?

EDIT: I tried this code: 编辑:我尝试此代码:

 floor, tile = maps.mapData[mapIndex][x][y]

 #draw floor
 if floor == 0: c.blit(maps.grass, tileRect)

 #draw tiles
 if tile == 1: c.blit(maps.tallGrass, tileRect)

and got the error: 并得到错误:

TypeError: 'int' object is not iterable

Thanks to @LukasGraf, the problem has been solved. 感谢@LukasGraf,问题已解决。 Not all the variables in the list were initialized as tuples, so I changed this initialization code 并非列表中的所有变量都被初始化为元组,因此我更改了此初始化代码

mapData = [[[0 for y in range(19)] for x in range(25)] for m in range(mapAmount)]

to this 对此

mapData = [[[(0, 0) for y in range(19)] for x in range(25)] for m in range(mapAmount)]

to make the default value in the list the tuple (0, 0) instead of 0. 使列表中的默认值成为元组(0,0)而不是0。

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

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