Question

List slicing was never my strongest aspect in Python, and I'm at a bit of a loss.

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. 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.

Was it helpful?

Solution

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; the arguments to slices are, as with range, [start:stop:step].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top