简体   繁体   English

如何简化此列表?

[英]How can I simplify this list?

List slicing was never my strongest aspect in Python, and I'm at a bit of a loss. 列表切片从来都不是我在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('#')

This is part of my code for cellular automata map generation for a simple roguelike. 这是我的细胞自动机地图生成代码的一部分,用于简单的roguelike。 That long ugly statement can be simplified, somehow. 漫长的丑陋声明可以通过某种方式简化。 I thought that temp = [ grid[x-1::3][y-1], grid[x-1::3][y], grid[x-1::3][y+1] ] would work, but I get index out of range errors. 我认为temp = [ grid[x-1::3][y-1], grid[x-1::3][y], grid[x-1::3][y+1] ]工作,但索引超出范围错误。

If I understand correctly, I think you want: 如果我理解正确,我想你想要:

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

The slices you are trying to use: 您尝试使用的切片:

l[n::3]

would take every third item from index n of l to the end; 将采取从索引每第三项nl到端部; the arguments to slices are, as with range , [start:stop:step] . range ,slice的参数为[start:stop:step]

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

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