python中列表的方格坐标点排序

2024-09-29 00:16:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个9×9正方形的网格。周围是一个更大的广场。方形角的坐标按以下方式存储在列表中:

# upper left corner = x1 y1
# lower left corner = x2 y2
# lower right corner = x3 x3
# upper right corner = x4 y4

我的清单:

^{pr2}$

我知道我可以在角落里

my_list[0][0]
> [x1 y1]

例如和值:

my_list[0][0][0]
> x1 

my_list[0][0][1]
> y1

但是,我不知道如何对列表进行排序,因为我有这样一个排序列表:

[[square1][square2][square3]...[square8][square9]
 [square10][square11][square12]...[square17][square18]
 .
 .
 .
 [square72][square73][square74]...[square80][square81]]

square1应该是x1和y1最低的正方形。对吗,我只需要第一个,也许是左上角?因为网格正方形的长度和宽度是一样的。在


Tags: right网格列表排序myleftupperlower
1条回答
网友
1楼 · 发布于 2024-09-29 00:16:19

您可以将带有形状(9,9,2)的my_list展平到具有形状(1,81,2)的一维列表,对其进行排序,然后将其重塑为原始形状。在

flat_list = [item for row in my_list for item in row]
flat_list.sort()

# If you want to reshape the 1d list with shape(1, 81, 2) to 2d list with shape(9, 9, 2)
result = []
temp = []
count = 0

for item in flat_list:
    temp.append(item)
    count += 1
    if count % 9 == 0:
        result.append(temp)
        temp = []
        count = 0

# You also can use numpy to reshape flat_list to (9, 9, 2)
import numpy to np
result = np.array(flat_list).reshape(9, 9, 2)

相关问题 更多 >