你如何从更大的2d列表中获得2d子列表?
gridx = 10
gridy = 16
grid = [[0]*gridx for i in range(gridy)]
subgrid = None
# I want to get a subgrid given an x,y grid origin (bottom-left) and x,y subgrid size
答案 0 :(得分:4)
如果你想在极限x1,y1,x2,y2切片你的2D列表,你可以这样做:
def getsubgrid(x1, y1, x2, y2, grid):
return [item[x1:x2] for item in grid[y1:y2]]
例如:
grid = [[1, 2, 3, 4, 5, 6, 7, 8, 9],
[11,12,13,14,15,16,17,18,19],
[21,22,23,24,25,26,27,28,29],
[31,32,33,34,35,36,37,38,39],
[41,42,43,44,45,46,47,48,49],
[51,52,53,54,55,56,57,58,59]]
print getsubgrid(3,2,5,4,grid)
#prints [[24, 25], [34, 35]]
答案 1 :(得分:1)
我假设您的网格存储在列表列表中?那就是:
primary list: [ * * * * * * ]
second item: * * * * * *
如果是这样,您的答案就是从起点到终点遍历这些列表。
sublist = []
for x in range(startx, endx):
sublist.append(oldlist[x][starty:endy])