Python slice assignment changes nearby element in list

时间:2015-12-08 19:24:29

标签: python python-3.x

I define Time.now array of bools like this:

n x n

This function sets rectangular region of that grid to state (True or False)

grid = [[False for x in range(n)] for x in range(n)] 

Region is defined by 2 corner points def set_region(grid, points, state): x1, y1, x2, y2 = points row = [state] * (x2 - x1 + 1) for y in range (y1, y2 + 1): grid[y][x1:x2] = row and (x1, y1)
(x2, y2) corresponds to row, y is a column

When I'm using this function to set whole region to x, it works fine, but when I'm trying to change it to True, it changes, but next element in row after changed element becomes False

Example:

True

The last assertion hereby fails. Why?

2 个答案:

答案 0 :(得分:2)

羞辱我。 Python中切片的结束索引是独占的。这很好用

grid[y][x1:x2+1] = row

答案 1 :(得分:1)

问题是你的set_range是+1,他们最终会把握更多东西到抓地力,全部删除,除非那是欲望的行为......