Python:将列表推导式转换为x,y列表

3

我正在为一个2D游戏使用两个区间来放置瓷砖,因此我创建了一个“tilemap”...

tilemap = [ [TILE for w in range(MAPWIDTH)] for h in range(MAPWIDTH)]

这个可以运作……现在我想要附加一个叫做“piecemap”的类的实例,对应于tilemap。为了做到这一点,我有一个名为Piece的类,代码如下:

class Piece():
   otherstuff = "string"
   location = [0,0] 

我想知道如何使用列表推导式将宽度范围中的"w"和高度范围中的"h"加载到"location"属性中。目前我的尝试(不起作用)看起来是这样的...

piecemap = [[Piece.location[0] for w in range(MAPWIDTH)],[Piece.location[1] for h in range(MAPHEIGHT)]

我知道这不对,但不知道该如何改正!有什么帮助吗?


你期望的输出是什么? - Anand S Kumar
5个回答

5
class Piece():
   otherstuff = "string"
   location = [0,0] 

这是一个非常奇怪的类。你有类属性otherstufflocation,就好像每个创建的Piece都会占据相同的位置。

相反,您可能想要实例属性,如下所示:

class Piece:
    def __init__(self, x, y, name="Unspecified"):
        self.location = [x,y]
        self.otherstuff = name

那么你的列表推导式看起来是这样的:
tilemap = [ [Piece(w, h) for w in range(MAPWIDTH)] for h in range(MAPWIDTH)]

2
当然,在一个地方将索引命名为 hw,而在另一个地方将其命名为 xy 可能会导致您的索引顺序倒转,就像我在这里所做的那样。 - Robᵩ

2

根据我所读的,我认为位置是每个Piece实例的属性(不是类属性)。名称属性也是如此(可能是)。 因此,在创建这些对象时,我会设置位置:

class Piece():
    otherstuff = "string"
    def __init__(self,x,y):
        self.location = [x, y]
        # self.otherstuff = name # add it to the parameters if that's the case

piecemap = [[Piece(w,h) for h in range(MAPWIDTH)] for w in range(MAPHEIGHT)]

1
你需要类似这样的东西:
>>> [[x,y] for x in range(3) for y in range(2)]
[[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]]

在你的情况下,它可能是这样的:
piecemap = [[Piece.location[0], Piece.location[1]] for w in range(MAPWIDTH)] for h in range(MAPHEIGHT)]

但我不确定你真正期望什么。

1
我不知道你为什么需要Piece类,但你可以使用zip函数检索所有位置:
piecemap = zip(range(MAPWIDTH), range(MAPHEIGHT))

1
您是否希望得到这样的结果:
tilemap = [(w, h) for w in range(MAPWIDTH) for h in range(MAPWIDTH)]
MAPWIDTH = 3
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
然后您就可以创建自己的“Piece”对象了?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接