繁体   English   中英

Python:将列表理解列入x,y列表

[英]Python: List comprehension into an x,y list

我正在使用两个范围在第二场比赛中放置牌,所以我创建了一个'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)]

我知道这是错的,但不知道如何做对! 任何帮助?

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)]

根据我的阅读,我假设该位置是每个Piece instance的属性(不是类属性)。 name属性(可能)也是如此。 因此,我会在创建此类对象时设置位置:

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)]

我不知道你需要Piece类,但你可以使用zip函数检索所有位置:

piecemap = zip(range(MAPWIDTH), range(MAPHEIGHT))

你需要这样的东西:

>>> [[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)]

但我不确定你真正期待的是什么

你不想要这样的东西:

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)

然后你可以创建你的“片断”对象?

暂无
暂无

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

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