Python 得到一个“sub”来自更大的二维列表的二维列表?

发布于 2024-12-07 20:02:05 字数 221 浏览 1 评论 0原文

如何从更大的 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

How would you get a 2d sublist from a bigger 2d list?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千纸鹤带着心事 2024-12-14 20:02:05

如果您想在限制 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]]

If you want to slice your 2D list at the limits x1, y1, x2, y2 you can do:

def getsubgrid(x1, y1, x2, y2, grid):
    return [item[x1:x2] for item in grid[y1:y2]]

for example:

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]]
度的依靠╰つ 2024-12-14 20:02:05

我假设您的网格存储在列表列表中?也就是说:

primary list: [ * * * * * * ]
second item:    * * * * * * 

如果是这样,您的答案是从起点到终点遍历这些列表。

sublist = []
for x in range(startx, endx):
     sublist.append(oldlist[x][starty:endy])

I assume your grid is stored in a list of lists? That is:

primary list: [ * * * * * * ]
second item:    * * * * * * 

If so, your answer is a walk across these lists, from your start point, to your endpoint.

sublist = []
for x in range(startx, endx):
     sublist.append(oldlist[x][starty:endy])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文