[英]How can I simplify this list?
列表切片从来都不是我在Python中最强的方面,我有点茫然。
for x in range(1, width-1):
for y in range(1, height-1):
temp, walls = [], 0
temp = [[ grid[x-1][y-1], grid[x][y-1], grid[x+1][y-1] ],
[ grid[x-1][y], '@', grid[x+1][y] ],
[ grid[x-1][y+1], grid[x][y+1], grid[x+1][y+1] ]]
for l in temp: walls += l.count('#')
这是我的细胞自动机地图生成代码的一部分,用于简单的roguelike。 漫长的丑陋声明可以通过某种方式简化。 我认为temp = [ grid[x-1::3][y-1], grid[x-1::3][y], grid[x-1::3][y+1] ]
工作,但索引超出范围错误。
如果我理解正确,我想你想要:
temp = [l[y-1:y+2] for l in grid[x-1:x+2]] # extract local data
temp[1][1] = "@" # replace centre
walls = sum(l.count("#") for l in temp) # count walls
您尝试使用的切片:
l[n::3]
将采取从索引每第三项n
的l
到端部; 与range
,slice的参数为[start:stop:step]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.